0

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?

4

2 Answers 2

7

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?

Sign up to request clarification or add additional context in comments.

2 Comments

Love the explanation that keys are always retrieved as strings :) that's something that many people will miss at first glance.
Danke :-) This is the best solution.
1

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....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.