[英]For-in with a hard-coded array
Rookie JS question here: 菜鸟JS问题在这里:
for( var p in ['nodeName', 'nodeType', 'tagName', 'localName'] ) {
console.log( p + '=' + all[i][p] + '\n' );
}
I expected to see something like 我希望看到类似的东西
nodeName=DIV
Instead, I get 相反,我得到
0=undefined
Am I forced to assign the array to a variable, so that I can index into it? 我是否被迫将数组分配给变量,以便可以对其进行索引? Is there a way to use this syntax in the for-in and retrieve the string from the array? 有没有办法在for-in中使用此语法并从数组中检索字符串?
Thanks! 谢谢!
Using for..in
for an array is almost always wrong . 对数组使用for..in
几乎总是错误的 。 It iterates over object properties, not over values -s so in your case it yields you 0, 1, 2 and 3. It gets even worse if you decide to extend Array.prototype
with custom methods (which, unlike extending Object.prototype
is not a big no-go). 它遍历对象属性,而不是遍历值-s,因此在您的情况下,它会产生0、1、2和3。如果决定使用自定义方法扩展Array.prototype
,则情况变得更糟 (与扩展Object.prototype
不同的是,不是很大的尝试)。 Their names will also be iterated over when using for..in
. 当使用for..in
时,它们的名称也将被迭代。
The proper way to do what you want is this: 做您想要的事情的正确方法是:
var foo = [...];
for(var i = 0; i < foo.length; i++) {
// use foo[i]
}
or this (in modern browsers or with the function being shim'd): 或以下内容(在现代浏览器中或带有伪装功能的情况下):
[...].forEach(function(value) {
// use value
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.