将多个项压入对象数组



原谅我,因为我还是新手,所以我希望我解释一下,这样你就明白了

我想将多个项目推入addItem函数(例如)console.log("forks", "laptop", "juice")我只能把第一项推进去。如果我把字符串分成单独的参数,当我回调函数时,我只得到最后一个参数。

const cart = {
contents: [],
addItem(item) {
cart.contents = (item) 
contents.push(...item); //tried it with and without the spread operator.
},
removeItem(deletedItem) {
delete cart.contents[deletedItem];
}
};
cart.addItem("laptop");
cart.addItem("guitar");
cart.addItem("phone");
cart.removeItem("guitar")
console.log(`The cart contains: ${cart.contents}`);

您必须将item设置为rest参数:

const cart = {
contents: [],
addItem(...item) {
this.contents.push(...item);
},
removeItem(deletedItem) {
this.contents.splice(this.contents.indexOf(deletedItem), 1);
}
};
cart.addItem("laptop", "guitar", "phone");
cart.removeItem("guitar")
console.log(`The cart contains: ${cart.contents}`);

同样,不要使用delete来删除项。请使用splice()

你非常接近展开操作符,你的代码只需要一点改变,有了这个改变,你可以传递多个项目作为分隔值,甚至一个数组与多个项目,甚至多个数组与多个值。

它们最终总是一个普通的字符串数组,这是你的工作代码。

const cart = {
contents: [],
addItem: (...items) => {
cart.contents = [...cart.contents, ...items];
},
removeItem(deletedItem) {
this.contents.splice(this.contents.indexOf(deletedItem), 1);
}
};
// multiple values
cart.addItem("laptop", "guitar", "phone");
console.log(`The cart contains: ${cart.contents}`);
// array of values
cart.addItem(['new laptop', 'new guitar', 'new phone']);
console.log(`The cart contains: ${cart.contents}`);
// multiple arrays
cart.addItem(['inner laptop1', 'inner guitar1', 'inner phone1'], ['inner laptop2', 'inner guitar2', 'inner phone2'], ['inner laptop3', 'inner guitar3', 'inner phone3']);
console.log(`The cart contains: ${cart.contents}`);

最新更新