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

这是我知道的唯一方法:

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

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

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


当前回答

这里是Array.indexOf的JavaScript 1.6兼容实现:

if (!Array.indexOf) {
    Array.indexOf = [].indexOf ?
        function(arr, obj, from) {
            return arr.indexOf(obj, from);
        } :
        function(arr, obj, from) { // (for IE6)
            var l = arr.length,
                i = from ? parseInt((1 * from) + (from < 0 ? l : 0), 10) : 0;
            i = i < 0 ? 0 : i;
            for (; i < l; i++) {
                if (i in arr && arr[i] === obj) {
                    return i;
                }
            }
            return -1;
        };
}

其他回答

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

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

这绝不是最好的,但我只是在发挥创意,加入到曲目中。

不要使用此

Object.defineProperty(Array.prototype,“exists”{值:函数(元素,索引){var索引=索引||0返回索引==this.length-1:this[index]==元素?索引:this.exists(元素,++索引)}})//输出1console.log(['one','two'].exists('two'));//输出-1console.log(['one','two'].existes('tree'));console.log(['one','two','three','four'].exists('fur'));

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

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

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

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

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