看来我不明白JavaScript中in
关键字的含义。
看看这个代码片段(http://jsfiddle.net/3LPZq/):
var x = [1,2]
for(i in x){
document.write(x[i]);
}
在 jsfiddle 中运行时,它不仅会打印数组中包含的值,还会打印数组对象的所有属性和方法。
当我这样更改它时 ( http://jsfiddle.net/4abmt/ ):
$(document).ready(function(){
var x = [1,2]
for(i in x){
document.write(x[i]);
}});
它只打印值 1 和 2。
为什么会这样?这是由 jQuery 引起的还是 in
关键字的行为取决于文档是否完全加载?
最佳答案
这是因为原型(prototype)继承。对象不仅显示其自身的属性,还显示其所有祖先的属性。
要仅查找对象自身的属性,请使用 obj.hasOwnProperty(prop)
。
var x = [1,2];
for (var i in x) {
if (x.hasOwnProperty(i)) {
document.write(x[i]);
}
}
请参阅 hasOwnProperty 上的 MDN 文档.
关于javascript - 使用 "in"关键字迭代 Javascript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7119169/