您可以添加接受另一辆车对象作为参数,如果汽车有给出的成员属性的值相同,则返回true成员方法。
Ex。
function Car(make, model, year, owner) {
this.make = make;
this.model = model;
this.year = year;
this.owner = owner;
this.isSameMake = function(otherCar){
return this.make === otherCar.make;
}
this.printCar = function() { // added this method to easily print all the data about car
return "Make: " + this.make + "<br>" +
"Model: " + this.model + "<br>" +
"Year: " + this.year + "<br>" +
"Owner: " + this.owner + "<hr>";
}
}
此外,我认为这将是更明智的那些车对象添加到数组,因此您可以通过所有的人都轻松地重复和他们的价值观有比较for循环。
var allCars = [];
allCars.push(new Car('eagle', 'Talon TSi', 1993, rand));
allCars.push(new Car('nissan', '300ZX', 1992, ken));
allCars.push(new Car('nissan', '54353', 2001, barbie));
allCars.push(new Car('nissan', 'XT', 2012, sam));
allCars.push(new Car('eagle', 'GT', 2011, owen));
allCars.push(new Car('eagle', '9', 2014, finn));
然后你可以做的是通过所有的汽车该数组中遍历什么,并创建与该名称的新阵列使,如果它不已经exsists并将其添加到字典中,像这样:
var carsByMake = {};
for(var i=0; i<allCars.length; i++){
if(carsByMake[allCars[i].make] == null){ // if there is no array with the current car make in the dictionary
var newMake = []; // create a new array
newMake.push(allCars[i]); // add current car to it
carsByMake[allCars[i].make] = newMake; // add the array to the dictionary with the key of the current car make
}
else{
carsByMake[allCars[i].make].push(allCars[i]); // else just add to dictionary with the key of current car make
}
}
之后,您可以遍历字典,并通过它的关键字获取存储在其中的所有对象,例如carsByMake [“nissan”]将存储包含make nissan等所有汽车的数组。 您按以下方式迭代字典:
for(var key in carsByMake){ // iterate through dictionary
for(var i=0; i<carsByMake[key].length; i++){ // get all the elements in the current list in dictionary
document.write("carsByMake[" + key + "][" + i + "] = " + carsByMake[key][i].printCar() + "<br>");
}
}
这将打印出:
carsByMake[eagle][0] = (Make: eagle, Model: Talon TSi, Year: 1993, Owner: rand)
carsByMake[eagle][1] = (Make: eagle, Model: GT, Year: 2011, Owner: owen)
carsByMake[eagle][2] = (Make: eagle, Model: 9, Year: 2014, Owner: finn)
carsByMake[nissan][0] = (Make: nissan, Model: 300ZX, Year: 1992, Owner: ken)
carsByMake[nissan][1] = (Make: nissan, Model: 54353, Year: 2001, Owner: barbie)
carsByMake[nissan][2] = (Make: nissan, Model: XT, Year: 2012, Owner: sam)
正如你所看到的鹰之作所有的汽车通过的“鹰”的密钥存储在字典中,和日产的所有汽车制造是通过“日产”键存储在字典中。
我试图避免重复的代码 –