找出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

其他回答

想一想,如果您多次调用此调用,那么使用关联数组Map使用哈希函数进行查找会更有效。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

可以使用具有方法“has()”的Set:

函数包含(arr,obj){var proxy=新集合(arr);if(proxy.has(obj))返回true;其他的return false;}var arr=['快乐','新','年'];console.log(包含(arr,'Happy'));

这可能是一个详细而简单的解决方案。

//plain array
var arr = ['a', 'b', 'c'];
var check = arr.includes('a');
console.log(check); //returns true
if (check)
{
   // value exists in array
   //write some codes
}

// array with objects
var arr = [
      {x:'a', y:'b'},
      {x:'p', y:'q'}
  ];

// if you want to check if x:'p' exists in arr
var check = arr.filter(function (elm){
    if (elm.x == 'p')
    {
       return elm; // returns length = 1 (object exists in array)
    }
});

// or y:'q' exists in arr
var check = arr.filter(function (elm){
    if (elm.y == 'q')
    {
       return elm; // returns length = 1 (object exists in array)
    }
});

// if you want to check, if the entire object {x:'p', y:'q'} exists in arr
var check = arr.filter(function (elm){
    if (elm.x == 'p' && elm.y == 'q')
    {
       return elm; // returns length = 1 (object exists in array)
    }
});

// in all cases
console.log(check.length); // returns 1

if (check.length > 0)
{
   // returns true
   // object exists in array
   //write some codes
}

现代浏览器具有Array#includes,这正是做到这一点的,除IE外,所有人都广泛支持它:

console.log(['joe','jane','mary']includes('jane]))//真的

您也可以使用Array#indexOf,它不那么直接,但对于过时的浏览器不需要polyfill。

console.log(['joe','jane','smary'].indexOf('jane')>=0)//真的


许多框架也提供类似的方法:

jQuery:$.inArray(value,array,[fromIndex])Undercore.js:_.inclus(数组,值)(别名为_.include和_.includes)DojoToolkit:Dojo.indexOf(array,value,[fromIndex,findLast])原型:array.indexOf(value)MooTools:array.indexOf(value)MochiKit:findValue(数组,值)MS Ajax:array.indexOf(值)Ext:Ext.Array.contains(数组,值)Lodash:_.includes(array,value,[from])(是_.包含4.0.0之前的版本)Ramda:R.includes(值,数组)

请注意,一些框架将其作为函数实现,而另一些框架将该函数添加到数组原型中。

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

/*
 * @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