我正在尝试构造addTopping方法,以便它可以采用多个浇头而不是一个推入toppings数组。我不确定该如何解决。我看过其他一些使用.push.apply()
的帖子,因为它创建了一个对象,因此在我的情况下不起作用。
class Pizza {
constructor(size, crust, stuffedcrust) {
this.size = size;
this.crust = crust;
this.stuffedcrust = stuffedcrust;
this.toppings = ["Cheese"];
}
addTopping(topping) {
this.toppings.push(topping);
}
removeTopping(topping) {
let index = this.toppings.indexOf(topping);
this.toppings.splice(index, 1);
}
}
let pizza1 = new Pizza("Medium", "thin", true);
pizza1.addTopping("Pepperoni", "Green Peppers", "Mushrooms");
console.log(pizza1);
pizza1.addTopping
到现在只会添加第一项。
答案 0 :(得分:4)
使用rest parameters收集数组中的所有addToppings()
参数,并使用spread syntax将数组转换为Array.push()
函数的参数:
class Pizza {
constructor(size, crust, stuffedcrust) {
this.size = size;
this.crust = crust;
this.stuffedcrust = stuffedcrust;
this.toppings = ["Cheese"];
}
addToppings(...toppings) { // rest
this.toppings.push(...toppings); // spread
}
removeTopping(topping) {
let index = this.toppings.indexOf(topping);
this.toppings.splice(index, 1);
}
}
let pizza1 = new Pizza("Medium", "thin", true);
pizza1.addToppings("Pepperoni", "Green Peppers", "Mushrooms");
console.log(pizza1);
答案 1 :(得分:1)
也许看看rest parameters。我想它将为您带来想要的东西
答案 2 :(得分:0)
您可以使用 function.arguments ,但已弃用。
来源: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Function/arguments