Javascript for-in 循环异常行为
Javascript for-in loop bizarre behavior
突然,我看到了一个奇怪的行为。
这是一个片段:
// attributesList is an object with properties 0, 1, 2.
for (var j in attributesList) {
// this loop should run 3 times.
var attribute = attributesList[j];
}
从上面可以看出,循环应该运行 3次。但由于某些非常奇怪的原因,它被 运行 4 次。对于最后一次迭代,j == "seek".
的值
更奇怪的是,这个相同的代码库适用于另一个 git 分支(没有变化)。这似乎只有当我从特定的 git 分支 运行 时才会发生。
这个神秘的"seek"属性有什么合乎逻辑的解释吗?
我尝试研究的一件事可能是 javascript 版本和任何其他版本差异......但这里没有运气。
* 已更新 *
attributesList 是对象类型数组。
有问题的对象有四个 可枚举属性。它可能从其原型对象继承 seek
,这就是为什么您认为它只有三个属性。
你对 MikeC 的评论增加了分量:
when I evaluate the attributesList during run/debug time I do not see any property called "seek"
你的更新也是如此:
attributesList is an array of object type.
这告诉我们,在您的代码库中的某处(可能在插件中),有人非常顽皮并添加了一个 enumerable 属性 到 Array.prototype
.他们可以使用各种不同的语法来做到这一点;如果只是属性(seek
),大概是这样的:
Array.prototype.seek = function() {
// ...
};
这是不好的做法,他们应该让它不可枚举:
Object.defineProperty(Array.prototype, "seek", {
value: function() {
// ...
}
});
但从根本上说,for-in
不适用于遍历数组。有关如何遍历数组的信息,请参阅 my other answer here。
从那个长答案中摘录两段:
使用forEach
:
attributesList.forEach(function(attribute) {
// ...
});
或者如果你真的想使用 for-in
,添加一个 hasOwnProperty
检查:
for (var j in attributesList) {
if (attributesList.hasOwnProperty(j)) {
// this loop should run 3 times.
var attribute = attributesList[j];
}
}
或者当然使用 for
循环。有关详细信息,请参阅 the answer。
突然,我看到了一个奇怪的行为。 这是一个片段:
// attributesList is an object with properties 0, 1, 2.
for (var j in attributesList) {
// this loop should run 3 times.
var attribute = attributesList[j];
}
从上面可以看出,循环应该运行 3次。但由于某些非常奇怪的原因,它被 运行 4 次。对于最后一次迭代,j == "seek".
的值更奇怪的是,这个相同的代码库适用于另一个 git 分支(没有变化)。这似乎只有当我从特定的 git 分支 运行 时才会发生。
这个神秘的"seek"属性有什么合乎逻辑的解释吗? 我尝试研究的一件事可能是 javascript 版本和任何其他版本差异......但这里没有运气。
* 已更新 *
attributesList 是对象类型数组。
有问题的对象有四个 可枚举属性。它可能从其原型对象继承 seek
,这就是为什么您认为它只有三个属性。
你对 MikeC 的评论增加了分量:
when I evaluate the attributesList during run/debug time I do not see any property called "seek"
你的更新也是如此:
attributesList is an array of object type.
这告诉我们,在您的代码库中的某处(可能在插件中),有人非常顽皮并添加了一个 enumerable 属性 到 Array.prototype
.他们可以使用各种不同的语法来做到这一点;如果只是属性(seek
),大概是这样的:
Array.prototype.seek = function() {
// ...
};
这是不好的做法,他们应该让它不可枚举:
Object.defineProperty(Array.prototype, "seek", {
value: function() {
// ...
}
});
但从根本上说,for-in
不适用于遍历数组。有关如何遍历数组的信息,请参阅 my other answer here。
从那个长答案中摘录两段:
使用forEach
:
attributesList.forEach(function(attribute) {
// ...
});
或者如果你真的想使用 for-in
,添加一个 hasOwnProperty
检查:
for (var j in attributesList) {
if (attributesList.hasOwnProperty(j)) {
// this loop should run 3 times.
var attribute = attributesList[j];
}
}
或者当然使用 for
循环。有关详细信息,请参阅 the answer。