I want to use function with while to print only 10 numbers starting from the number I choose.
But while loop doesn't stop looping.
id = prompt('Write any number.');
function numbering(a) {
var i = a;
var j = a + 10;
while (i < j) {
document.write(i);
i++;
}
};
numbering(id);
Try this:
var id = parseInt(prompt('Write any number.'), 10);
In your example id will be of type string and the comparisons won't work as you expect.
When you use function numbering(a) {, the variable a is passed as string.
This results in i and j being set as string.
Taking example:
Suppose you pass 2 as input, your variables will be set as a="2", i="2" and j="210". So according to your condition, it'll print starting from 2 till 209.
You can change your code to parse a as number to achieve your result; something like:
function numbering(a) {
a = parseInt(a); //parse as Int here
var i=a; var j=a+10;
while (i < j)
{
document.write(i);
i++;
}
};
Try it with a for-loop:
for(var i=0; i<10; i++){ doSomething}
You can try with this for-loop function :
id=prompt('Write any number.');
function numbering(a) {
for (let i = a; i < a + 10; i++){
document.write(i);
}
};
numbering(id);
You can add a parseInt(id) to you numbering function parameter call if you want to parse the input into a number
When you enter a number in the prompt, it is supplied as a string. Since you have not converted this into a number, the line var j = a + 10 is actually joining the two values as if they were strings.
For example, if you enter "5" into the prompt, then var j = "5" + 10 returns "510". Only when you then compare the two variables in the while loop with i < j does it get interpreted as a number, and will loop from 5 to 510.
The easiest way to convert a string into a number is to use parseInt(value).
The prompt function returns a string.
The problem is that you are concatenating a string with the number 10.
If you write your variables to document, you can see the problem:
id=prompt('Write any number.');
function numbering(a) {
var i=a; var j=a+10;
document.write(i);
document.write("<br/>");
document.write(j);
document.write("<br/>");
//while (i < j){
// document.write(i);
// i++;
//}
};
numbering(id);
This will fix your problem:
var id=parseInt(prompt('Write any number.'));
you need the parseInt function because what you getting from promt is string. For example 5 +10 . For javascript , it will be 510 .
id=prompt('Write any number.');
function numbering(a) {
var i=parseInt(a); var j=parseInt(a)+10;
while (i < j){
document.write(i);i++;
}};
numbering(id);
document.write(i +"<br>");
In console i am getting proper result. just add line break to see whole result in viewport
Related
I am trying to solve a challenge from Codewars where you have to find the number in an array that appears odd number of times. I modified my answer to return the number that appears odd number of times and is most frequent. But it always results in 0
counts={};
function findOdd(A) {
for (var i=0; i<A.length; i++){
if ((typeof counts["a" + toString(A[i])]) !== 'undefined'){
counts["a" + toString(A[i])]++;
}
else{
counts["a" + toString(A[i])]=1;
}
}
max = 0;
for (a in counts){
if (counts[a]>max && counts[a]%2!==0){
max = counts[a]
}
}
return max;
}
var testArray=[];
for (var i =0; i<100; i++){
testArray.push(Math.ceil(Math.random()*100))
}
console.log(findOdd(testArray));
The issue is in toString(). It's not a normal, global function but it actually is a shortcut to window.toString().
You don't actually need toString() for the cases you are using it, Javascript will automatically convert the value to a string for cases like this:
'a' + 5; // equals 'a5'.
I want to iterate through a string until a null character is found (\0), like how we do in C language. I have listed down the steps which I have tried below.
let exampleValue = 'abcdef';
let i = 0;
// Trial 1
while (exampleValue[i] !== '\0') {
i++;
// This seems to go on infinitely
}
// Trial 2
while (exampleValue[i] !== '\0'.charCodeAt(0)) {
i++;
// This seems to go on infinitely
}
// Trial 3
while (exampleValue[i] !== \0) {
i++;
// This throws an invalid character error
}
// Trial 4
while (exampleValue[i] !== undefined) {
i++;
// This seems to work
}
Based on the above samples, Trial 4 seems to work. Can I continue using Trial 4 for my desired output or is there a better way to solve my problem?
EDIT:
I apologize for not specifying my problem, I want to print each letter of the string by iterating through it without using exampleValue.length
EDIT 2:
After I read tadman's comment, I got to know Javascript's do not terminate their string using a null character but instead it stores it's keeps track of it characters and stores the length seperately.
If you just want to count the length then just do exampleValue.length
let exampleValue = 'abcdef';
let i = exampleValue.length;
console.log(i);
Or if you want to perform some logic using that char, you can try:
let exampleValue = 'abcdef';
let i = 0;
exampleValue.split('').forEach(c => {
console.log(c);
i++;
// Your logic here.
});
console.log(i);
Or using plain for loop:
let exampleValue = 'abcdef';
let i = 0;
for (let x = 0; x < exampleValue.length; x++) {
console.log(exampleValue.charAt(i));
i++;
// Your logic here.
}
console.log(i);
You are getting these cases because you will never get an '\0' in your string so the loop will run infinitely.
And the last case is working fine because after the last character of your string, the next character will be undefined.
Now, if you want to loop through the string then you can do it this way:
let exampleValue = 'abcdef';
let i = 0;
while (i < exampleValue.length ) {
console.log(exampleValue[i]);
i++;
}
Since you didn't say exactly what you realy want... If you want to print the individual characters,
let exampleValue = 'abcdef';
for(var j = 0; j < exampleValue.length; j++){
console.log(exampleValue[j]);
}
And if you are just interested in the number of elements:
int i = exampleValue.length;
console.log(i)
I'm doing Udacity javascript studies now and there is one quiz that bothers me. I know how to do it easily in ruby, but this one is killing me.
I need to call function and return "ha" num times and add "!" at the end with the loop.
I tried this but it didn't help. Should be very simple.
function laugh(num) {
for (var x = 0; num; x ++) {
return 'ha';
}
}
console.log(laugh(3));
Actually you don't even need the loop.
const laugh = num => 'ha'.repeat(num) + '!';
console.log(laugh(3));
console.log(laugh(5));
Returning in a loop will return the whole function. To make this work you could concatenate the string in the loop and then return the concatenated output. You also formatted your loop incorrectly, you need to tell the loop to stop when x is less than num. Try:
function laugh(num) {
var laughString = '';
for (var x = 0; x < num; x++) {
laughString += 'ha';
}
return laughString + '!';
}
console.log(laugh(3));
You can only return once from a function. Try building up the string you need in the loop, then return the value after the loop is done.
(Note: You can have multiple return statements in a function, but as soon as you hit one of them the function completes its execution.)
function laugh(num) {
var outString = '';
for (var x = 0; x<num; x ++) {
outString += ' ha';
}
return outString.substring(1) + '!';
}
console.log(laugh(3));
function laugh(input) {
var answer = '';
for (var i = 0; i < input; i++) {
answer += 'ha';
}
return (answer + '!');
}
First, set a variable to an empty string, (it will be your answer)
Then, write a for loop that loops according to the input (you did that)
then inside the for loop you add 'ha' to your answer string
finally outside the for loop (after it has ran all the loops)
return the answer string plus !
i'm filling an array from the input fields and i need to find the biggest number in that array.
Using Math.max(myData) gives me NaN error and when i'm using the "if" statement,sometimes it works and sometimes it doesn't.
Example: if i have 40 and 100 in array ,it gives me 40 as bigger number,but when i have 500 than it works fine.
if i want to make Math.max to work i need to make a new function that converts string into numbers,right?
my code,so you can see where is the mistake.
function Data() {
var h = 0;
var secnd = 1;
var najBr = 0;
for (var i = 0; i < valGrup2; i++)
{
var first = 1;
myDataName[i] = document.getElementById('ime' + secnd).value;
for (var j = 0; j < val2; j++)
{
myData[h] = document.getElementById("inputpolja" + first + secnd).value;
if(myData[h]>najBr){
najBr=myData[h];
}
myDataValue[h] = document.getElementById("inputpolja" + first + secnd).value;
h++;
first++;
}
secnd++;
}
//najBr=Math.max(myData);
console.log(najBr);
Math.max accepts only plain numbers, not an array.
Use this:
function getMaxOfArray(numArray) {
return Math.max.apply(null, numArray);
}
Math.max takes multiple arguments, not an array of the numbers. You can use Function#apply() to have it treat the array as a list of arguments:
Math.max.apply(null /* the context */, myData)
So I have a string called hoursString that looks like
4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|
I split the string into an array and what I am trying to do is add up all the numbers and return it to the html page in the div "test".
JAVASCRIPT:
var hours=hoursString.split("|");
var total=0;
for (var i=0;i<hours.length;i++)
{
total += hours[i];
}
document.getElementById("test").innerHTML=total;
The result is NaN. Can someone tell me what I am doing wrong?
Thanks!
4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|
remove the last |, split will otherwise add an empty string at the end of the array which will give NaN and NaN + number evaluates to NaN
edit: and yes, parseFloat is necessary too, otherwise the result will be a string instead of NaN
var hoursString = "4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|",
hours = hoursString.split("|"),
total = 0;
for (var i = 0; i < hours.length; i++) {
total += parseFloat(hours[i]) || 0; // see explanation
}
document.getElementById("test").innerHTML = total;
Why the || 0? Because it checks if the string is "", if so the || operand will return the second value, in this case 0.
This will output 25.740000000000002. See this answer on the cause of the "wrong" result, and here is a working fiddle.
Your issue is that each element in hours is still a string value even though it is written as a number. The easiest way to fix this would be to use javascripts parseFloat() function.
Example:
var hours=hoursString.split("|");
var total=0;
for (var i=0;i<hours.length;i++)
{
total += parseFloat(hours[i]);
}
document.getElementById("test").innerHTML=total;
EDIT: Changed from parseInt to parseFloat
var hoursString = "4.3|2.4|3.4|3.0|2.64|3.0|1.0|0.0|2.6|3.4|"
var hours=hoursString.split("|");
var total=0;
var idx = 0;
for(idx in hours) {
total += +hours[idx];
}
alert(total);
FIDDLE