javascript for 循环计数器作为字符串出现 [英] javascript for loop counter coming out as string

查看:23
本文介绍了javascript for 循环计数器作为字符串出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将我的程序简化为这个,但它仍然有问题:

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);
    }
}

似乎row是一个字符串而不是一个整数,例如输出是

It seems that row is a string instead of an integer, for example the output is

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

而不是 5、6、7、8,这是我想要的.for 循环中的计数器不应该是字符串吗?

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

推荐答案

引用自 for..in 的 MDN 文档,

Quoting from MDN Docs of for..in,

for..in 不应该用于迭代 Array 其中索引顺序很重要. 数组索引只是可枚举的属性整数名称,在其他方面与一般对象相同特性.不能保证 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.

因为迭代的顺序是依赖于实现的,迭代在一个数组上可能不会以一致的顺序访问元素.所以最好使用带有数字索引的 for 循环(或 Array.forEach或非标准的 for...of 循环)当迭代数组时访问顺序很重要.

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 进行迭代时,您得到的是字符串格式的数组索引.

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.

所以在每次迭代中,'0' + 5 == '05', '1' + 5 == '15'...正在打印

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

你应该做的是,

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 for 循环计数器作为字符串出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆