javascript for 循环计数器以字符串形式出现

标签 javascript string for-loop

我已将我的程序简化为这样,但它仍然运行不正常:

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

关于javascript for 循环计数器以字符串形式出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22479386/

相关文章:

javascript - 使用ajax将时间以秒为单位传递给div

ruby - 这个串联的运算顺序是什么?

java - startsWith() 无法与 '§' 字符正常工作

Python在循环中将数字相加

javascript - jQuery toLowerCase 然后应用 Capitalize CSS Style

javascript - 使用js库内部缓存的数据

parameters - 在 verilog 中使用带有 for 循环的参数进行位选择

for循环中的Python变量范围

javascript - 在页面加载时触发 Javascript 文本和图片预览

ios - 如何将 Swift UIDatePicker 转换为字符串,然后检查另一个日期