You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

原生JS电商项目:API存入数组后无法访问元素返回undefined

问题分析:无法访问电商系统产品数组的元素

我用原生JavaScript开发简易电商系统完成作业,创建了Product类与ClassListProducts类。调用FakeStoreAPI获取产品数据后,实例化Product并添加到ClassListProducts的lista数组中,但无法访问数组特定元素(返回undefined),也无法遍历该数组,请问原因是什么?

代码示例

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]);

问题原因

核心问题是异步操作的执行顺序:

  • fetch是异步网络请求,它不会阻塞后续代码执行。你写的console.log会在fetch请求完成、数据处理完毕之前就先运行,此时lista数组还是初始的空数组,自然访问lista[0]会返回undefined。
  • 另外你的ClassListProducts构造函数里this.addProduct.bind()是无效代码,因为没有把绑定后的函数赋值给this.addProduct,不过这里你是直接通过listProducts.addProduct()调用,this指向是正确的,所以这个问题没影响当前功能。

解决方案

把需要访问数组的代码放到fetch的then回调里,确保在数据处理完成后再执行:

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

或者使用async/await让代码逻辑更直观:

async function loadProducts() {
  const res = await fetch("https://fakestoreapi.com/products");
  const json = await res.json();
  json.forEach(({ title, id }) => {
    listProducts.addProduct(id, title);
  });
  console.log(listProducts.lista);
  console.log(listProducts.lista[0]);
}

loadProducts();

内容的提问来源于stack exchange,提问作者matias poses

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 19:08:10