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

const cart = {
  contents: [],
  addItem() {

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

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

评论
  • 紫涙嘫
    紫涙嘫 回复

    Use push:

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

    If you want to pass multiple items like addItem("laptop", "phone"), use spreading:

    const cart = {
      contents: [],
      addItem(...items) {
        this.contents.push(...items);
      }
    };
    cart.addItem("laptop", "phone");
    console.log("The cart contains:", cart.contents);
  • yquo
    yquo 回复

    You could do like this this.contents.push(item)

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