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

其他回答

function contains(a, obj) {
    return a.some(function(element){return element == obj;})
}

Array.prototype.some()在第5版中被添加到ECMA-262标准中

正如其他人提到的,您可以使用Array.indexOf,但并非所有浏览器都可以使用。这是来自的代码https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf以使其在旧浏览器中工作相同。

indexOf是ECMA-262标准的最新添加;因此,它可能并非在所有浏览器中都存在。您可以通过插入脚本开头的以下代码,允许使用indexOf在本机不支持它的实现中。这算法完全是ECMA-262第5版中规定的算法,假设Object、TypeError、Number、Math.floor、Math.abs和Math.max具有其原始价值。

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this == null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 1) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}

类似的事情:通过“search lambda”查找第一个元素:

Array.prototype.find = function(search_lambda) {
  return this[this.map(search_lambda).indexOf(true)];
};

用法:

[1,3,4,5,8,3,5].find(function(item) { return item % 2 == 0 })
=> 4

咖啡脚本也一样:

Array.prototype.find = (search_lambda) -> @[@map(search_lambda).indexOf(true)]

有几种方法可以找到答案。您可以使用内置的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.
*/

我查看了提交的答案,发现只有通过引用搜索对象时,这些答案才适用。具有参考对象比较的简单线性搜索。

但是,假设您没有对象的引用,如何在数组中找到正确的对象?您必须对每个对象进行线性和深度比较。想象一下,如果列表太大,并且其中的对象非常大,包含大量文本。随着阵列中元素的数量和大小,性能急剧下降。

您可以将对象字符串化并将其放入本机哈希表中,但这样您就有了记住这些键的数据冗余,因为JavaScript将它们保存为“for i in obj”,您只需要检查对象是否存在,也就是说,您拥有该键。

我考虑了一段时间来构建一个JSON模式验证器,我为本地哈希表设计了一个简单的包装器,类似于唯一的哈希表实现,但一些优化异常我留给本地哈希表处理。它只需要性能基准。。。所有详细信息和代码都可以在我的博客上找到:http://stamat.wordpress.com/javascript-quickly-find-very-large-objects-in-a-large-array/我将很快发布基准结果。

完整的解决方案如下所示:

var a = {'a':1,
 'b':{'c':[1,2,[3,45],4,5],
 'd':{'q':1, 'b':{'q':1, 'b':8},'c':4},
 'u':'lol'},
 'e':2};

 var b = {'a':1, 
 'b':{'c':[2,3,[1]],
 'd':{'q':3,'b':{'b':3}}},
 'e':2};

 var c = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

 var hc = new HashCache([{a:3, b:2, c:5}, {a:15, b:2, c:'foo'}]); //init

 hc.put({a:1, b:1});
 hc.put({b:1, a:1});
 hc.put(true);
 hc.put('true');
 hc.put(a);
 hc.put(c);
 hc.put(d);
 console.log(hc.exists('true'));
 console.log(hc.exists(a));
 console.log(hc.exists(c));
 console.log(hc.exists({b:1, a:1}));
 hc.remove(a);
 console.log(hc.exists(c));