我有一个对象数组,我可以将它们一起 console.log 但是当我想访问特定元素时返回 undefined

问题描述 投票:0回答:0

你好在 javascript vanilla 中为商店编写代码以进行分配。我正在做一个简单的电子商务,我创建了两个类(Product 和 ClassListProducts),然后我使用了一个 api。使用此 api,我创建了一个类产品并将其推送到 ClassListProducts 数组。我也不能循环数组。我的问题是为什么我不能访问数组中的特定元素,它返回未定义。

class Product {
  constructor(id, name) {
    this.id = id;
    this.name = name;
  }
}
class ClassListProducts {
  constructor() {
    this.lista = [];
    this.addProduct.bind();
  }

  addProduct(id, name) {
    let producto = new Product(id, name);
    this.lista.push(producto);
  }
}
const listProducts = new ClassListProducts();

fetch("https://fakestoreapi.com/products")
  .then((res) => res.json())
  .then((json) =>
    json.forEach(({ title, id }) => {
        listProducts.addProduct(id, title);
    })
  );

console.log(listProducts.lista);
console.log(listProducts.lista[0]);

screenshot of the console.log

对不起我的英语。

我尝试使用一个 api 并将产品保存在一个对象中,然后将它们保存在数组中。我想访问具体元素。

javascript arrays object
© www.soinside.com 2019 - 2024. All rights reserved.