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

这是我知道的唯一方法:

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

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

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


当前回答

现代浏览器具有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

好的,你可以优化你的代码来得到结果!

有很多方法可以做到这一点,它们更干净、更好,但我只是想获得您的模式,并使用JSON.stringify应用于此,只需在您的情况下执行以下操作:

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

2019年更新:这个答案来自2008年(11岁!),与现代JS用法无关。承诺的性能改进基于当时浏览器中的基准测试。它可能与现代JS执行上下文无关。如果您需要一个简单的解决方案,请寻找其他答案。如果您需要最佳的性能,请在相关的执行环境中进行基准测试。

正如其他人所说,通过数组迭代可能是最好的方法,但事实证明,递减while循环是JavaScript中迭代最快的方法。因此,您可能需要按如下方式重写代码:

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

当然,您还可以扩展Array原型:

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

现在,您可以简单地使用以下命令:

alert([1, 2, 3].contains(2)); // => true
alert([1, 2, 3].contains('2')); // => false

它有一个参数:对象的数组数。数组中的每个对象都有两个由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;}}警报(计数);

有几种方法可以找到答案。您可以使用内置的Array方法。最常用的是数组查找方法。

const arr1 = [1, 2, 3, 4, 5]
const result = arr1.find(ele => ele === 4)
console.log(result) //4

const result2 = arr1.find(ele => ele === 6)
console.log(result2) //undefined
/* 
If the element is present inside the array
then it will return the first element that
satisfies the given condition. Otherwise
undefined will return.
*/