将多个项目推入对象数组

pushing multiple items into an object array

请原谅我,因为我还是新手,所以我希望我解释的很有意义

我想将多个项目推送到 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 parameter:

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}`);