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

这是我知道的唯一方法:

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

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

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


当前回答

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

不要使用此

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'));

其他回答

而array.indexOf(x)=-1是实现这一点的最简洁的方法(并且已经被非Internet Explorer浏览器支持了十多年……),它不是O(1),而是O(N),这很可怕。如果您的数组不会改变,您可以将数组转换为哈希表,然后执行表[x]==未定义或==未定义:

Array.prototype.toTable = function() {
    var t = {};
    this.forEach(function(x){t[x]=true});
    return t;
}

演示:

var toRemove = [2,4].toTable();
[1,2,3,4,5].filter(function(x){return toRemove[x]===undefined})

(不幸的是,虽然您可以创建Array.prototype.contains来“冻结”数组并将哈希表存储在this._cache中,但如果您选择稍后编辑数组,则会产生错误的结果。与Python不同,JavaScript没有足够的钩子来保持这种状态。)

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

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

使用Array.indexOf(对象)。对于ECMA7,可以使用Array.includes(对象)。使用ECMA 6,可以使用Array.find(FunctionName),其中FunctionName是用户定义函数以搜索数组中的对象。希望这有帮助!

这个需求的简单解决方案是使用find()

如果您有以下对象数组,

var users = [{id: "101", name: "Choose one..."},
{id: "102", name: "shilpa"},
{id: "103", name: "anita"},
{id: "104", name: "admin"},
{id: "105", name: "user"}];

然后可以检查具有您的值的对象是否已存在:

let data = users.find(object => object['id'] === '104');

如果数据为空,则没有admin,否则它将返回现有对象,如:

{id: "104", name: "admin"}

然后,您可以在数组中找到该对象的索引,并使用以下代码替换该对象:

let indexToUpdate = users.indexOf(data);
let newObject = {id: "104", name: "customer"};
users[indexToUpdate] = newObject;//your new object
console.log(users);

您将获得如下值:

[{id: "101", name: "Choose one..."},
{id: "102", name: "shilpa"},
{id: "103", name: "anita"},
{id: "104", name: "customer"},
{id: "105", name: "user"}];

有两种方法使这一点很容易实现(包括,一些,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