views:

200

answers:

4

or do you just have to do a loop and check each element ?

+6  A: 

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;
  };
}
meder
A: 

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.

James Black
+5  A: 

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

Update: Pointed URL to new jQuery API

jeerose
A: 

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;
      })
    );
Dan Breslau