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.(这种方法也适用于数组,但是在数组上使用时,比第一种选择要慢一些。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…