【发布时间】:2014-02-05 14:01:06
【问题描述】:
我一直在向我们项目的主 JavaScript 文件添加一个 Array.indexOf() 填充。我从 devdocs.io 获取的:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement , fromIndex) {
var i,
pivot = (fromIndex) ? fromIndex : 0,
length;
if (!this) {
throw new TypeError();
}
length = this.length;
if (length === 0 || pivot >= length) {
return -1;
}
if (pivot < 0) {
pivot = length - Math.abs(pivot);
}
for (i = pivot; i < length; i++) {
if (this[i] === searchElement) {
return i;
}
}
return -1;
};
}
我需要这个,因为我们仍然必须支持 IE 8,但似乎在 IE 8 中,indexOf() 函数被添加为可枚举的。这意味着,它会在使用 for..in 循环遍历数组时出现,如下所示:
var a = [];
a[0]=123;
a[1]=456;
for(var value in a) {
alert(value); // this even alerts "indexOf", if the polyfill above is loaded, and this is a big problem
}
是否可以使 polyfill “不可枚举”,以便我能够在 IE 8 中使用 Array.indexOf(),但它不会出现在 for..in 循环中?
【问题讨论】:
-
我认为 for ... in ... 对数组来说不是一个好主意:stackoverflow.com/questions/500504/…
-
这里的解决方案是停止使用
for...in来迭代一个Array。请改用简单的for循环。 -
我无法改变我们的代码中有数百个 for..in 循环在数组上的事实。改变它们将是一项巨大的工作。不过,polyfill 并没有在代码中出现这么久,删除它会相对容易......如果没有其他方法,我将不得不这样做。
-
@PaulMa 将代码移到 Array.prototype 之外是否可以接受?这包括以不同的方式称呼它。
-
我一直在和我的同事讨论这个问题,我们决定真的要让 polyfill 保持原样,我们将在每个 for-in 循环中检查 hasOwnProperty 函数的结果。感谢您的帮助!
标签: javascript arrays enumerable for-in-loop