9

I've simplified my program down to this, and it's still misbehaving:

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, for example the output is

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

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

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
stackers
  • 2,701
  • 4
  • 34
  • 66

3 Answers3

16

Quoting from MDN Docs of for..in,

for..in should not be used to iterate over an Array where index order is important. Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.

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

You are iterating an array with for..in. That is bad. When you iterate with for..in, what you get is the array indices in string format.

So on every iteration, '0' + 5 == '05', '1' + 5 == '15'... is getting printed

What you should be doing is,

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

For more information about why exactly array indices are returned in the iteration and other interesting stuff, please check this answer of mine

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
2

You should use a normal for loop rather than a for...in loop for arrays.

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

I think this is what your expected output should be.

Fiddle

Andy
  • 61,948
  • 13
  • 68
  • 95
-1

Try with parseInt(..) method to force int value

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

second param 10 is to be parsed as decimal value.

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

Community
  • 1
  • 1
Wundwin Born
  • 3,467
  • 19
  • 37