JavaScript循环计数器出来的字符串 [英] javascript for loop counter coming out as string
问题描述
var grid = [0,1, 2,3];
函数moveUp(moveDir){
for(var row in grid){
console.log('row:');
console.log(row + 5);
pre $ row $ / code>是一个字符串而不是整数,例如输出是
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
行:
15
行:
25
行:
35
而不是5,6,7,8,这正是我想要的。 for循环中的计数器不应该是一个字符串吗?
从 MDN文件 for..in
,
for..in
不应该用于迭代Array
其中索引顺序
非常重要。数组索引只是具有
整数名称的可枚举属性,其他方面与通用Object
属性相同。不能保证for ... in将以任何特定的顺序返回
索引,并且它将返回所有可枚举的
属性,包括那些非整数名称和那些是
继承。
由于迭代顺序是依赖于实现的,所以在数组上迭代
可能无法以一致的顺序访问元素。因此,
最好使用带有数字索引的for循环(或Array.forEach
或非标准的for ... of
循环)迭代数组,其中
的访问顺序是重要的。
您正在迭代的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);
$ b 有关为什么在迭代中返回数组下标和其他有趣的更多信息东西,请检查我的这个答案
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?
解决方案 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
这篇关于JavaScript循环计数器出来的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!