问题描述
考虑以下代码:
var arr = [111, 222, 333];
for(var i in arr) {
if(i === 1) {
// Never executed
}
}
它会失败,因为typeof i === 'string'
.
有没有办法解决这个问题?我可以显式地将 i
转换为整数,但这样做似乎违背了使用更简单的 for in
而不是常规的 for
循环的目的.
Is there way around this? I could explicitly convert i
to integer, but doing so seems to defeat the purpose using simpler for in
instead of regular for
-loop.
我知道相比之下使用 ==
,但这不是一个选项.
I am aware of using ==
in comparison, but that is not an option.
推荐答案
你有几个选择
转换为数字:
Make conversion to a Number:
parseInt(i) === 1
~~i === 1
+i === 1
不要比较类型(使用 ==
而不是 ===
):
i == 1 // Just don't forget to add a comment there
将 for 循环更改为(我会这样做,但这取决于您要实现的目标):
Change the for loop to (I would do this but it depends on what you are trying to achieve):
for (var i = 0; i < arr.length; i++) {
if (i === 1) { }
}
// or
arr.forEach(function(item, i) {
if (i === 1) { }
}
顺便说一下,您不应该使用 for...in
来遍历数组.请参阅文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
By the way you should not use for...in
to iterate through an array. See docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
for..in 不应用于迭代索引顺序的数组很重要.数组索引只是可枚举的属性整数名称,在其他方面与一般对象相同特性.不能保证 for...in 会返回任何特定顺序的索引,它将返回所有可枚举的属性,包括那些具有非整数名称的属性和那些继承.
因为迭代的顺序是依赖于实现的,迭代在一个数组上可能不会以一致的顺序访问元素.所以最好使用带有数字索引的 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) 循环索引是字符串而不是整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!