Javascript has an exists () or contains () function for an array

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

+3
source share
4 answers

If you use jQuery: jQuery.inArray (value, array)

Update : Specified URL for new jQuery API

+5
source

Mozilla JS implementations and other modern JS systems have adopted the method Array.prototype.indexOf.

[1].indexOf(1) // 0

if it does not contain it, it returns -1.

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

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;
  };
}
+6
source

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

Source: https://habr.com/ru/post/1728558/


All Articles