找出JavaScript数组是否包含值的最简洁有效的方法是什么?

这是我知道的唯一方法:

function contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}

有没有更好、更简洁的方法来实现这一点?

这与堆栈溢出问题密切相关。在JavaScript数组中查找项目的最佳方法是什么?它解决了使用indexOf查找数组中的对象的问题。


当前回答

如果您使用ES6,您可以使用一组:

function arrayHas( array, element ) {
    const s = new Set(array);
    return s.has(element)
}

这应该比任何其他方法都更有效

其他回答

Use:

function isInArray(array, search)
{
    return array.indexOf(search) >= 0;
}

// Usage
if(isInArray(my_array, "my_value"))
{
    //...
}

原型是这样做的:

/**
 *  Array#indexOf(item[, offset = 0]) -> Number
 *  - item (?): A value that may or may not be in the array.
 *  - offset (Number): The number of initial items to skip before beginning the
 *      search.
 *
 *  Returns the position of the first occurrence of `item` within the array &mdash; or
 *  `-1` if `item` doesn't exist in the array.
**/
function indexOf(item, i) {
  i || (i = 0);
  var length = this.length;
  if (i < 0) i = length + i;
  for (; i < length; i++)
    if (this[i] === item) return i;
  return -1;
}

另请参见此处了解它们是如何连接的。

使用Array.prototype.includes,例如:

常量水果=['conot','香蕉','苹果']const doesFruitsHaveCoconut=水果.包括('conot')//trueconsole.log(doesFruitsHaveCoconut)

可以从MDN阅读此文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

检查数组JavaScript中是否存在值的最佳默认方法是some()

Array.prototype.some()

some()方法测试数组中是否至少有一个元素通过了所提供函数实现的测试。如果在数组中找到所提供的函数返回true的元素,则返回true;否则返回false。它不会修改数组。

const array = [1, 2, 3, 4, 5];

// checks whether an element is even
const even = (element) => element % 2 === 0;

console.log(array.some(even));
// expected output: true

some方法是浏览器兼容性中最好的方法

有关更多文档Array.prototype.some()-JavaScript | MDN

您还可以使用另外两个方法:find()和includes()。用这些方法你可以得到你的结果,但不是最好的。

Array.prototype.find()-JavaScript | MDN

Array.prototype.includes()-JavaScript | MDN

如果你使用的是JavaScript 1.6或更高版本(Firefox 1.5或更高),你可以使用Array.indexOf。