Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

javascript for loop counter coming out as string

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...