Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

javascript - 如何确定对象是否在数组中(How to determine if object is in array [duplicate])

This question already has an answer here:(这个问题已经在这里有了答案:)

How do I check if an array includes a value in JavaScript?(如何检查数组是否在JavaScript中包含值?) 47 answers(47个答案)

I need to determine if an object already exists in an array in javascript.(我需要确定JavaScript中的数组中是否已存在对象。)

eg (dummycode):(例如(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); now the "carBrands" array contains all instances.(现在,“ carBrands”数组包含所有实例。) I'm now looking a fast solution to check if an instance of car1, car2, car3 or car4 is already in the carBrands array.(我现在正在寻找一种快速解决方案,以检查car1,car2,car3或car4的实例是否已经在carBrands数组中。) eg:(例如:) var contains = carBrands.Contains(car1); //<--- returns bool. car1 and car4 contain the same data but are different instances they should be tested as not equal.(car1和car4包含相同的数据,但是是不同的实例,应该测试它们是否相等。) Do I have add something like a hash to the objects on creation?(我是否在创建时向对象添加了像哈希这样的东西?) Or is there a faster way to do this in Javascript.(还是有更快的方法来执行此操作。) 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.(我正在这里寻找最快的解决方案,如果它很脏,那么它必须是;)在我的应用程序中,它必须处理大约10000个实例。) no jquery(没有jQuery)   ask by Caspar Kleijne translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use something like this:(使用这样的东西:)

function containsObject(obj, list) { var i; for (i = 0; i < list.length; i++) { if (list[i] === obj) { return true; } } return false; } In this case, containsObject(car4, carBrands) is true.(在这种情况下, containsObject(car4, carBrands)为true。) Remove the carBrands.push(car4);(删除carBrands.push(car4);) call and it will return false instead.(调用,它将返回false。) 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.(这种方法也适用于数组,但是在数组上使用时,比第一种选择要慢一些。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...