2010-01-15 78 views

回答

6

Mozilla JS实现和其他现代JS引擎采用了Array.prototype.indexOf方法。

[1].indexOf(1) // 0 

如果它不包含它,则返回-1。

当然,IE和其他可能的浏览器不拥有它,因为它的官方代码:

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; 
    }; 
} 
0

你可以看一下JavaScript 1.6中某些功能。

https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Working_with_Arrays#Introduced_in_JavaScript_1.6

如果你只是想知道这是否是在那里,你可以使用indexOf例如,这将满足您的需求。

UPDATE:

如果你去这个页面,http://www.hunlock.com/blogs/Mastering_Javascript_Arrays,你可以找到在IE和不具有一个内置的,你要使用功能的任何其它浏览器中使用的功能。

0

这里是有自己的indexOf方法的一种方式。如果它存在于环境中,则此版本利用Array.prototype.indexOf方法;否则,它使用自己的实现。

(此代码已经过测试,但我不保证其正确性的所有情况。)

// If Array.prototype.indexOf exists, then indexOf will contain a closure that simply 
// calls Array.prototype.indexOf. Otherwise, indexOf will contain a closure that 
// *implements* the indexOf function. 
// 
// The net result of using two different closures is that we only have to 
// test for the existence of Array.prototype.indexOf once, when the script 
// is loaded, instead of every time indexOf is called. 

var indexOf = 
    (Array.prototype.indexOf ? 
    (function(array, searchElement, fromIndex) { 
     return array.indexOf(searchElement, fromIndex); 
    }) 
    : 
    (function(array, searchElement, fromIndex) 
     { 
      fromIndex = Math.max(fromIndex || 0, 0); 
      var i = -1, len = array.length; 
      while (++i < len) { 
       if (array[i] === searchElement) { 
        return i; 
       } 
      } 
      return -1; 
     }) 
    ); 
相关问题