Javascript for loop counter coming out as string

I simplified my program to this and it is still wrong:

var grid = [0, 1, 2, 3]; function moveUp(moveDir) { for (var row in grid) { console.log('row:'); console.log(row + 5); } } 

It seems that row is a string instead of an integer, e.g. output

 row: 05 row: 15 row: 25 row: 35 

not 5, 6, 7, 8, which is what I want. Shouldn't the counter in a for loop be a string?

+8
javascript string for-loop
source share
3 answers

Quote from MDN for..in ,

for..in should not be used to iterate over Array , where index order is Important. Array indices are simply enumerated properties with integer names and are otherwise identical to the common property object. There is no guarantee that for ... in indices in any particular order, and it will return all enumerated properties, including those with non-integer names and those that are inherited.

Since the iteration order is implementation dependent, iterating over an array cannot visit elements in sequential order. Therefore, it is better to use a for loop with a numerical index (or Array.forEach or a non-standard for...of loop) when iterating over arrays where the access order is important.

We iterate the array using for..in . This is bad. When you iterate with for..in , you get the array indices in string format.

So, at each iteration, '0' + 5 == '05' , '1' + 5 == '15' ... is printed

What you gotta do

 for (var len = grid.length, i = 0; i < len; i += 1) { console.log('row:'); console.log(grid[i] + 5); } 

For more information on why exactly the same array indices are returned on iterations and other interesting things, please check this my answer

+13
source share

You should use a regular for loop, not a for...in loop for...in arrays.

 for (var row = 0, l = grid.length; row < l; row++) { console.log('row:'); console.log(5 + row); } 

I think this is your expected result.

Fiddle

+2
source share

Try using the parseInt (..) method to force an int value

 console.log(parseInt(row,10) + 5); 

second parameter 10 should be parsed as a decimal value.

See the answer here How do I add an integer value with javascript (jquery) to a value that returns a string?

0
source share

All Articles