开发者

does javascript have an exists() or contains() function for an array

or do you just have to do a loop and che开发者_如何学Pythonck each element ?


Mozilla JS implementations and other modern JS engines have adopted an Array.prototype.indexOf method.

[1].indexOf(1) // 0

if it doesn't contain it, it returns -1.

IE of course and possibly other browsers do not have it, the official code for it:

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


If you're using jQuery: jQuery.inArray( value, array )

Update: Pointed URL to new jQuery API


You can look at Javascript 1.6 for some functions.

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

If you just want to know if it is in there, you could use indexOf for example, which would meet your needs.

UPDATE:

If you go to this page, http://www.hunlock.com/blogs/Mastering_Javascript_Arrays, you can find a function to use on IE and any other browser that doesn't have a built in function that you want to use.


Here's one way to have your own indexOf method. This version leverages the Array.prototype.indexOf method if it exists in the environment; otherwise, it uses its own implementation.

(This code has been tested, but I don't guarantee its correctness for all cases.)

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜