如何确定对象是否在数组中 [英] How to determine if object is in array

查看:126
本文介绍了如何确定对象是否在数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定一个对象是否已经存在于javascript中的数组中。

I need to determine if an object already exists in an array in javascript.

例如(dummycode):

eg (dummycode):

var carBrands = [];

var car1 = {name:'ford'};
var car2 = {name:'lexus'};
var car3 = {name:'maserati'};
var car4 = {name:'ford'};

carBrands.push(car1);
carBrands.push(car2);
carBrands.push(car3);
carBrands.push(car4);

现在carBrands数组包含所有实例。
我现在正在寻找一个快速的解决方案来检查car1,car2,car3或car4的实例是否已经在carBrands数组中。

now the "carBrands" array contains all instances. I'm now looking a fast solution to check if an instance of car1, car2, car3 or car4 is already in the carBrands array.

例如:

var contains =  carBrands.Contains(car1); //<--- returns bool.

car1和car4包含相同的数据但不同的实例它们应该被测试为不相等。

car1 and car4 contain the same data but are different instances they should be tested as not equal.

我是否在创建对象时添加了类似哈希的东西?或者有更快的方法在Javascript中执行此操作。

Do I have add something like a hash to the objects on creation? Or is there a faster way to do this in Javascript.

我在这里寻找最快的解决方案,如果很脏,那么它必须是;)在我的应用程序中必须处理大约10000个实例。

I am looking for the fastest solution here, if dirty, so it has to be ;) In my app it has to deal with around 10000 instances.

没有jquery

推荐答案

使用类似的东西:

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

    return false;
}

在这种情况下, containsObject(car4,carBrands) 是真的。删除 carBrands.push(car4); 调用,它将返回false。如果你以后扩展到使用对象存储这些其他汽车对象而不是使用数组,你可以改用这样的东西:

In this case, containsObject(car4, carBrands) is true. Remove the carBrands.push(car4); call and it will return false instead. If you later expand to using objects to store these other car objects instead of using arrays, you could use something like this instead:

function containsObject(obj, list) {
    var x;
    for (x in list) {
        if (list.hasOwnProperty(x) && list[x] === obj) {
            return true;
        }
    }

    return false;
}

此方法也适用于数组,但在数组上使用时,它将是比第一个选项慢一点。

This approach will work for arrays too, but when used on arrays it will be a tad slower than the first option.

这篇关于如何确定对象是否在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆