Dae*_*mon 3 javascript arrays internet-explorer indexof
有很多关于如何将indexOf实现引入Array原型的解决方案,以便它可以在Internet Explorer下工作,但是我偶然发现了一个似乎无法在我看到的任何地方解决的问题.
// indexOf support for IE (from MDC)
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this && this[from] === elt)
return from;
}
return -1;
};
}
var i = [1,2,3,4];
for (j in i)
{
alert(i[j]);
}
Run Code Online (Sandbox Code Playgroud)
我期待收到4个警报,每个警报包含阵列的一个元素.在Firefox和Chrome中,这正是我所看到的,但是在IE8中,我得到一个包含indexOf功能代码的附加警报.
可以做些什么来避免这种情况?
发生这种情况是因为在IE中,由于该方法不存在,因此将其添加到Array.prototype,并且它仍然是可枚举的.
对于使用Arrays进行woking(通常是任何类似数组的对象),我不建议使用该for...in语句.
为什么?
for...in语句旨在枚举对象属性.for...in正如您所注意到的那样,该声明会爬上原型链.最简单的方法,简单的for循环:
for (var j = 0; j < i.length; j++) {
alert(i[j]);
}
Run Code Online (Sandbox Code Playgroud)
也可以看看: