将方法中的值放入属性数组中

问题描述 投票:0回答:2
const cart = {
  contents: [],
  addItem() {

  }
};
cart.addItem("laptop");
console.log("The cart contains:", cart.contents);

我如何将addItem方法中的项目放入内容属性数组?

javascript arrays reactjs object
2个回答
0
投票

您可以这样做this.contents.push(item)

const cart = {
  contents: [],
  addItem(item) {
     this.contents.push(item)
  }
};
cart.addItem("laptop");
console.log("The cart contains:", cart.contents);

0
投票

使用push

const cart = {
  contents: [],
  addItem(item) {
    this.contents.push(item);
  }
};
cart.addItem("laptop");
console.log("The cart contains:", cart.contents);

如果要传递addItem("laptop", "phone")之类的多个项目,请使用传播:

const cart = {
  contents: [],
  addItem(...items) {
    this.contents.push(...items);
  }
};
cart.addItem("laptop", "phone");
console.log("The cart contains:", cart.contents);
© www.soinside.com 2019 - 2024. All rights reserved.