我正在学习 javascript,我决定尝试使用方法、构造函数和this
关键字。我制作了一种方法来根据与属性值中的单词匹配的某些单词来查找汽车。如果结果是一个词匹配一个值,那么它返回那个对象。问题是,当多个对象具有相同的属性值时,只返回其中的第一个。如何让所有具有相同值的对象返回?可以简单解决还是解决方案真的很先进?我尝试了this
关键字的大量变体,但没有任何效果。
//The constructor
function car(make, model, year, condition){
this.make = make;
this.model = model;
this.year = year;
this.condition = condition;
}
//An object that holds properties that are really just more objects
var cars = {
car1: new car("Toyota", "Corolla", 2013, "New"),
car2: new car("Hyundai", "Sonata", 2012, "Used"),
car3: new car("Honda", "Civic", 2011, "Used")
};
//The method
findCar = function(find){
for(var i in cars){
if(cars[i].make.toLowerCase() === find){
return cars[i];
}
else if(cars[i].model.toLowerCase() === find){
return cars[i];
}
else if(cars[i].year === parseInt(find,10)){
return cars[i];
}
else if(cars[i].condition.toLowerCase() === find){
return cars[i];
}
}
};
cars.findCar = findCar;
//This is where I search for cars
cars.findCar(prompt("Enter a car make, model, year or condition").toLowerCase());