我已将我的程序简化为这样,但它仍然运行不正常:
var grid = [0, 1, 2, 3];
function moveUp(moveDir) {
for (var row in grid) {
console.log('row:');
console.log(row + 5);
}
}
似乎row
是一个字符串而不是一个整数,例如输出是
row:
05
row:
15
row:
25
row:
35
而不是 5、6、7、8,这是我想要的。 for 循环中的计数器不应该是一个字符串吗?
引自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.
您正在使用 for..in
迭代一个数组。那很不好。当您使用 for..in
进行迭代时,您得到的是字符串格式的数组索引。
因此在每次迭代中,'0' + 5 == '05'
、'1' + 5 == '15'
... 正在打印
你应该做的是,
for (var len = grid.length, i = 0; i < len; i += 1) {
console.log('row:');
console.log(grid[i] + 5);
}
有关为什么在迭代中准确返回数组索引和其他有趣内容的更多信息,请查看 this answer of mine