我有一个函数以及一个使用“ new”创建的实例:
function Cars (model, color, year) {
this.model = model;
this.color = color;
this.year = year;
this.allCars = [];
}
var bmw = new Cars('z4', 'white', 2010),
benz = new Cars('cl', 'black', 2011),
ford = new Cars('mustang', 'red', 2015),
audi = new Cars('s3', 'yellow', 2013),
fiat= new Cars('fat boy', 'purple', 2020);
Cars.prototype.addCars = function (data) {
for(let i=0; i<3; i++){
this.allCars.push(data);
return this.allCars;
}
}
console.log(benz.addCars(bmw,audi,fiat));
console.log(benz.addCars(ford));
我试图创建一个名为“ addCars”的函数,以便每当我为其分配一个实例时,例如benz.addCars(x1,x2,x3,...),我就能得到一个数组参数中提到的汽车数量。
例如,我希望在致电
时获得以下结果console.log(benz.addCars(bmw,audi,fiat))
// expected result: ['bmw','audi',fiat']
以及单个参数实例的以下结果:
console.log(benz.addCars(ford));
//expected result: ['ford']
我只是想知道如何使用addCard函数填充此数组。 欢呼
答案 0 :(得分:1)
您还可以考虑使用这样的类设置:
class Car {
constructor(brand, model, color, year) {
this._brand = brand
this._model = model
this._color = color
this._year = year
}
get brand() {
return this._brand
}
}
class Cars {
constructor(cars = []) {
this._cars = cars
}
addCars(cars) {
cars.forEach(c => this._cars.push(c))
}
getBrands() {
return this._cars.map(x => x.brand)
}
}
let cars = new Cars([
new Car('BMW', 'z4', 'white', 2010),
new Car('Mercedes', 'cl', 'black', 2011),
new Car('Ford', 'mustang', 'red', 2015),
new Car('Audi', 's3', 'yellow', 2013),
new Car('Fiat', 'fat boy', 'purple', 2020)
])
console.log(cars.getBrands())
可以在哪里使用ES6 getter / setters等。
这是设置的另一种方法:
function Cars(brand, model, color, year) {
this.brand = brand;
this.model = model;
this.color = color;
this.year = year;
this.allCars = [];
}
var bmw = new Cars('BMW', 'z4', 'white', 2010),
benz = new Cars('Mercedes', 'cl', 'black', 2011),
ford = new Cars('Ford', 'mustang', 'red', 2015),
audi = new Cars('Audi', 's3', 'yellow', 2013),
fiat = new Cars('Fiat', 'fat boy', 'purple', 2020);
Cars.prototype.addCars = function(data) {
if (Array.isArray(data)) {
for (let i = 0; i < data.length; i++) {
this.allCars.push(data[i]);
}
return data.map(x => x.brand)
} else {
this.allCars.push(data);
return data.brand
}
}
console.log(benz.addCars([bmw, audi, fiat]));
console.log(benz.addCars([ford]));
答案 1 :(得分:0)
请尝试以下方法/答案。
function Cars (model, color, year) {
this.model = model;
this.color = color;
this.year = year;
this.allCars = [];
}
var bmw = new Cars('z4', 'white', 2010),
benz = new Cars('cl', 'black', 2011),
ford = new Cars('mustang', 'red', 2015),
audi = new Cars('s3', 'yellow', 2013),
fiat= new Cars('fat boy', 'purple', 2020);
Cars.prototype.addCars = function (data) {
for(var i = 0; i < arguments.length; i++) {
this.allCars.push(arguments[i]);
}
return this.allCars;
}
console.log(benz.addCars(bmw,audi,fiat));
console.log(benz.addCars(ford));