[英]Javascript for-in statement
I'm trying to output the keys of an array in javascript like this: 我试图像这样在javascript中输出数组的键:
data=[8, 4, 6, 9, 5, 2, 4, 6];
for(i in data){console.log(i);}
But instead of only outputting the keys, it outputs this: 但是,它不仅输出键,还输出以下内容:
0
1
2
3
4
5
6
7
$family
each
clean
associate
link
contains
extend
getLast
getRandom
include
combine
erase
empty
flatten
hexToRgb
rgbToHex
min
max
average
sum
unique
shuffle
Why? 为什么? And how can I make it stop after outputting the array keys?
输出数组键后如何使其停止?
Use a "normal" for
loop instead: 用“正常”
for
循环,而不是:
for(var i = 0; i < data.length; i++) {
console.log(data[i]);
}
JavaScript's for...in
construct iterates over all properties of the object, so you get all of the properties/methods on Array.prototype
(in fact, it will go all the way up the prototype chain) as well as the elements you're expecting. JavaScript的
for...in
构造会迭代对象的所有属性,因此您会获得Array.prototype
上的所有属性/方法(实际上,它将一直Array.prototype
原型链)以及您所使用的元素重新期待。
This is because Arrays are objects, and for-in iterates properties, not by Array indices. 这是因为数组是对象,并且for-in迭代属性,而不是通过数组索引。 You could do this:
data.forEach(function(a,i){console.log(i);})
or you could examine the properties and see if they "in" Array.prototype 您可以这样做:
data.forEach(function(a,i){console.log(i);})
或检查属性,看看它们是否“在” Array.prototype中
A for..in
loop goes through all enumerable properties of an object. for..in
循环for..in
对象的所有可枚举属性。 I don't know how all those extra properties came to be defined on your array - are you using a library that adds them to Array.prototype
? 我不知道如何在您的数组上定义所有这些额外的属性-您是否正在使用将它们添加到
Array.prototype
的库?
You should use a traditional for loop to go through an array's numerically indexed items - this will automatically ignore any other properties. 您应该使用传统的for循环来遍历数组的数字索引项-这将自动忽略任何其他属性。 If you just want to output the indexes then something like:
如果只想输出索引,则类似于:
for (var i=0; i < data.length; i++) {
if (typeof data[i] !== "undefined")
console.log(i);
}
Note that .length
returns one higher than the highest defined index, but that doesn't mean that all lower indexes actually have a value in them so I've included a check that each item is not undefined. 请注意,
.length
返回的值比定义的最高索引高一个,但这并不意味着所有较低的索引实际上都具有一个值,因此我包括检查每个项是否均未定义的。 You can remove that if undefined is a valid value in your array - in practice I rarely use arrays with "holes" in them, but I mention it for completeness. 如果未定义是数组中的有效值,则可以删除该数组-在实践中,我很少使用在其中带有“孔”的数组,但出于完整性考虑,我将其提及。
PS You could use .forEach()
, but it isn't supported by older browsers. PS您可以使用
.forEach()
,但是旧版浏览器不支持。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.