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

这是我知道的唯一方法:

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

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

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


当前回答

它有一个参数:对象的数组数。数组中的每个对象都有两个由x和y表示的整数财产。该函数必须返回数组中满足numbers.x==numbers.y的所有此类对象的计数

var数=〔{x:1,y:1},{x:2,y:3},{x:3,y:3},{x:3,y:4},{x:4,y:5}];变量计数=0;var n=数字长度;对于(变量i=0;i<n;i++){如果(数字[i].x==数字[i].y){count+=1;}}警报(计数);

其他回答

使用indexOf()

可以使用indexOf()方法检查数组中是否存在给定的值或元素。如果找到数组中元素的索引,indexOf()方法返回该元素的索引;如果找不到,则返回-1。让我们看一下以下示例:

var fruits=[“苹果”、“香蕉”、“芒果”、“橙子”、“木瓜”];var a=“芒果”;checkArray(a,水果);函数checkArray(a,fruits){//检查fruits数组中是否存在值如果(fruits.indexOf(a)!==-1) {return document.write(“true”);}其他{return document.write(“false”);}}

使用include()方法

ES6引入了includes()方法来非常容易地执行此任务。但是,此方法只返回true或false,而不返回索引号:

var fruits=[“苹果”、“香蕉”、“芒果”、“橙子”、“木瓜”];警报(水果,包括(“香蕉”));//输出:真警报(水果,包括(“椰子”));//输出:假警报(水果,包括(“橙色”));//输出:真警报(水果,包括(“樱桃”));//输出:假

如需进一步参考,请在此处结账

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

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

现代浏览器具有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(值,数组)

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

除了其他人所说的之外,如果没有要在数组中搜索的对象的引用,那么可以执行类似的操作。

let array = [1, 2, 3, 4, {"key": "value"}];

array.some((element) => JSON.stringify(element) === JSON.stringify({"key": "value"})) // true

array.some((element) => JSON.stringify(element) === JSON.stringify({})) // true

如果任何元素与给定条件匹配,Array.some返回true;如果没有元素与给定的条件匹配,则返回false。

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

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

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