Reputation: 794
i have the following loop which is iterating through an array and i try to access the next position of the current position in the array.
for( var i in myArray){
var temp = myArray[i+1];
}
The problem is that it not add the 1 with the var i but it just appends the number 1 on the i. Like i is 2 and i do this
i+1
the result is
21
and not 3.
Why is this so and how can i add the two variables?
Upvotes: 0
Views: 95
Reputation: 386520
Basically you are iterating over the keys of an object (an array is an object) and the keys are always strings (or symbol type in ES6). For converting to a number, you could just add an unary plus
in front of it for converting a stringed number to a number.
var temp = myArray[+i + 1];
You might use better the classical iteration with a counter, like
var i, temp;
for (i = 0; i < array.length; i++) {
temp = array[i + 1];
// some more code
}
because for ... in
iterates over all enumerable properties of the object, if exist. For more information read Why is using “for…in” with array iteration a bad idea?
Upvotes: 7
Reputation: 219
Parseint should be used to add two varibles
var test1= parseInt(10);
var test2= parseInt(20);
alert(test1+test2); // should now alert 30
This is how you can add two variables in Javascript....
Upvotes: 1