我需要确定数组中是否存在一个值。

我正在使用以下函数:

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] == obj) {
            return true;
        }
    }
    return false;
}

上面的函数总是返回false。

数组值和函数调用如下所示:

arrValues = ["Sam","Great", "Sample", "High"]
alert(arrValues.contains("Sam"));

当前回答

var contains = function(needle) {
    // Per spec, the way to identify NaN is that it is not equal to itself
    var findNaN = needle !== needle;
    var indexOf;

    if(!findNaN && typeof Array.prototype.indexOf === 'function') {
        indexOf = Array.prototype.indexOf;
    } else {
        indexOf = function(needle) {
            var i = -1, index = -1;

            for(i = 0; i < this.length; i++) {
                var item = this[i];

                if((findNaN && item !== item) || item === needle) {
                    index = i;
                    break;
                }
            }

            return index;
        };
    }

    return indexOf.call(this, needle) > -1;
};

你可以这样使用它:

var myArray = [0,1,2],
    needle = 1,
    index = contains.call(myArray, needle); // true

CodePen验证/使用

其他回答

对于包含函数,最简单的解决方案是这样的函数:

var contains = function (haystack, needle) {
    return !!~haystack.indexOf(needle);
}

理想情况下,你不会让它成为一个独立的函数,而是helper库的一部分:

var helper = {};

helper.array = {
    contains : function (haystack, needle) {
        return !!~haystack.indexOf(needle);
    }, 
    ...
};

现在,如果你碰巧是那些不幸的人之一,仍然需要支持IE<9,因此不能依赖indexOf,你可以使用这个填充,这是我从MDN:

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(searchElement, fromIndex) {
    var k;
    if (this == null) {
      throw new TypeError('"this" is null or not defined');
    }
    var o = Object(this);
    var len = o.length >>> 0;
    if (len === 0) {
      return -1;
    }
    var n = +fromIndex || 0;

    if (Math.abs(n) === Infinity) {
      n = 0;
    }
    if (n >= len) {
      return -1;
    }
    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
    while (k < len) {
      if (k in o && o[k] === searchElement) {
        return k;
      }
      k++;
    }
    return -1;
  };
}

jQuery有一个实用函数:

$.inArray(value, array)

返回数组中值的索引。如果数组不包含值,则返回-1。

另参见如何检查数组中是否包含JavaScript对象?

Array.prototype.includes ()

在ES2016中,有Array.prototype.includes()。

includes()方法确定数组是否包含某个元素,根据需要返回true或false。

例子

["Sam", "Great", "Sample", "High"].includes("Sam"); // true

支持

根据kangax和MDN,支持以下平台:

Chrome 47 边缘14 Firefox 43 歌剧34 Safari 9 节点6

支持可以使用Babel(使用Babel -polyfill)或core-js扩展。MDN还提供了polyfill:

if (![].includes) {
  Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
    'use strict';
    var O = Object(this);
    var len = parseInt(O.length) || 0;
    if (len === 0) {
      return false;
    }
    var n = parseInt(arguments[1]) || 0;
    var k;
    if (n >= 0) {
      k = n;
    } else {
      k = len + n;
      if (k < 0) {k = 0;}
    }
    var currentElement;
    while (k < len) {
      currentElement = O[k];
      if (searchElement === currentElement ||
         (searchElement !== searchElement && currentElement !== currentElement)) {
        return true;
      }
      k++;
    }
    return false;
  };
}

这通常是indexOf()方法的用途。你会说:

return arrValues.indexOf('Sam') > -1

从ECMAScript6开始,可以使用Set:

var myArray = ['A', 'B', 'C'];
var mySet = new Set(myArray);
var hasB = mySet.has('B'); // true
var hasZ = mySet.has('Z'); // false