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

这是我知道的唯一方法:

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

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

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


当前回答

有两种方法使这一点很容易实现(包括,一些,find,findIndex)

常量数组=[1,2,3,4,5,6,7];console.log(array.includes(3));//includes()确定数组的条目中是否包含某个值console.log(array.some(x=>x===3));//some()测试数组中是否至少有一个元素通过了所提供函数实现的测试console.log(array.find(x=>x===3)?真:假);//find()返回所提供数组中满足所提供测试函数的第一个元素的值console.log(array.findIndex(x=>x===3)>-1);//findIndex()返回数组中满足所提供测试函数的第一个元素的索引,否则返回-1。

更多关于includes,some,find,findIndex

其他回答

复杂性O(n/2)

您可以使用任何库函数,但我使用的是核心JavaScript。如果返回true,我们首先搜索中间的元素,否则我们同时从左到中和从右到中搜索数组中的元素。因此,它将具有O(n/2)复杂性。并且它将返回true或false,指示它是否存在

let isExist = (arr, element)=> {
  let index = -1;
  if ((arr.length % 2 != 0) && arr[(arr.length-1)/2]===element) {
    index = 1;
    return true;
  }
  for(let i=0; i<Math.ceil(arr.length-1/2); i++){
    if (arr[i]===element || (arr[arr.length-i]===element)) {
      index = i;
      break;
    }
  }
  return (index<0)? false : true;
}



let array = ['apple', 'ball', 'cat', 'dog', 'egg']

console.log(isExist(array, 'yellow'));
//Result false because yellow doesn't exist in array
console.log(isExist(array, 'cat'));
//Result true because yellow exist in array

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

我们使用以下代码段(用于对象、数组和字符串):

/*
 * @function
 * @name Object.prototype.inArray
 * @description Extend Object prototype within inArray function
 *
 * @param {mix}    needle       - Search-able needle
 * @param {bool}   searchInKey  - Search needle in keys?
 *
 */
Object.defineProperty(Object.prototype, 'inArray',{
    value: function(needle, searchInKey){

        var object = this;

        if( Object.prototype.toString.call(needle) === '[object Object]' || 
            Object.prototype.toString.call(needle) === '[object Array]'){
            needle = JSON.stringify(needle);
        }

        return Object.keys(object).some(function(key){

            var value = object[key];

            if( Object.prototype.toString.call(value) === '[object Object]' || 
                Object.prototype.toString.call(value) === '[object Array]'){
                value = JSON.stringify(value);
            }

            if(searchInKey){
                if(value === needle || key === needle){
                return true;
                }
            }else{
                if(value === needle){
                    return true;
                }
            }
        });
    },
    writable: true,
    configurable: true,
    enumerable: false
});

用法:

var a = {one: "first", two: "second", foo: {three: "third"}};
a.inArray("first");          //true
a.inArray("foo");            //false
a.inArray("foo", true);      //true - search by keys
a.inArray({three: "third"}); //true

var b = ["one", "two", "three", "four", {foo: 'val'}];
b.inArray("one");         //true
b.inArray('foo');         //false
b.inArray({foo: 'val'})   //true
b.inArray("{foo: 'val'}") //false

var c = "String";
c.inArray("S");        //true
c.inArray("s");        //false
c.inArray("2", true);  //true
c.inArray("20", true); //false

我建议使用下划线库,因为它返回值,并且支持所有浏览器。

下芯js

 var findValue = _.find(array, function(item) {
    return item.id == obj.id;
 });

使用idnexOf()是一个很好的解决方案,但您应该隐藏嵌入的实现indexOf(()函数,该函数使用~运算符返回-1:

function include(arr,obj) { 
    return !!(~arr.indexOf(obj)); 
}