阵列的indexOf实施的Internet Explorer [英] Array indexOf implementation for Internet Explorer

查看:114
本文介绍了阵列的indexOf实施的Internet Explorer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多关于如何得到执行的indexOf入阵原型,以便它工作在Internet Explorer的解决方案,但是我已经在这似乎并没有解决任何地方我到目前为止已经看了一个问题绊倒

There are plenty of solutions on how to get the indexOf implementation into the Array prototype so that it works under Internet Explorer, however I've stumbled upon an issue that doesn't seem to be addressed anywhere I've looked so far.

在使用MDC 落实好商定的pretty一>,我有以下的code,现在的问题是:

Using the pretty well agreed upon implementation at MDC, I have the following code that's being problematic now:

// 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]);
}

我期望接收4警报,每一个含有数组的元素之一。
在Firefox和Chrome,这正是然而,我所看到的,在IE8我得到包含的indexOf函数code额外的警告。

I am expecting to receive 4 alerts, each one containing one of the elements of the array. In Firefox and Chrome, that's exactly what I see, however in IE8 I get an additional alert containing the indexOf function code.

可以做些什么来避免这种情况?

What can be done to avoid this?

推荐答案

这是因为你编辑Array.prototype,因此产生的任何阵列继承定做察觉的方法的indexOf 认为,在命令可以看到。

That's because you edit Array.prototype and thus any array created inherits the custom-made VISIBLE method indexOf that the "in" command can see.

的for..in 结构并不像例如PHP的的foreach - 它不只是遍历数组中的所有项目,而且迭代所有方法和属性的数组对象可能已经(在JavaScript中的数组实际上是伪装的对象)。本地方法是不可见的的for..in 结构,但所有的自定义添加都没有。

for..in construct in JavaScript doesn't act like for example PHP's foreach - it doesn't just iterate all the items in the array but also iterates all the methods and properties the array OBJECT might have (arrays in JavaScript are actually "disguised" objects). Native methods are invisible to the for..in construct but all the custom additions are not.

在你的榜样,任何数组是这样的:

In your example any array would look like this:

Array:
- [0] value
- [1] value
- [2] value
- ..
- [N] value
- [IndexOf] value

要避免非通缉继承的方法和属性,你可以使用的方法的hasOwnProperty()

To avoid the non-wanted inherited methods and properties you can use the method hasOwnProperty():

for (j in j){
    if(i.hasOwnProperty(j){
        alert(i[j])
    }
}

的hasOwnProperty 检查关键是不能继承,属于实际的对象。这种方式只需要的值通过。

hasOwnProperty checks if the key is not inherited and belongs to the actual object. This way only the needed values pass through.

这篇关于阵列的indexOf实施的Internet Explorer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆