简体   繁体   English

在 JavaScript 中将项目添加到对象数组中

[英]Add an item into an array of an object in JavaScript

Here's the code:这是代码:

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

I want to obviously add the item "laptop" into the property "contents" of the object "cart" and for the console.log to display that information.我想明显地将项目“笔记本电脑”添加到对象“购物车”的属性“内容”中,并让 console.log 显示该信息。 I think all I need is for the "addItem(item)" method to know WHERE ("contents: [],") exactly to add these items bc right now it seems like it points to nothing?我认为我需要的只是让“addItem(item)”方法知道 WHERE (“contents: [],”) 正是为了添加这些项目 bc 现在它似乎没有指向任何东西? Any help would be awesome.任何帮助都是极好的。 Thanks.谢谢。

In your addItem method, do this:在您的addItem方法中,执行以下操作:

 addItem(item) {
    this.contents.push(item)
 }

This accesses the object's contents via this , and adds the item to the array.这通过this访问对象的内容,并将项目添加到数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM