You need to enable JavaScript to run this app. 如何使用.map()方法遍历从API获取的两个不同数组并完成页面渲染
优惠活动
大模型
产品
解决方案
定价
更多

如何使用.map()方法遍历从API获取的两个不同数组并完成页面渲染

原代码核心缺陷
  • 逗号运算符误用:dataArray[(0, 1)]是JavaScript的逗号运算符语法,会从左到右执行表达式,最终返回最后一个值,这里等价于dataArray[1],只会遍历Prices数组,完全拿不到Products里的ProductType、ProductDescription等字段,自然无法生成正确的商品卡片。
  • 关联数组逻辑处理错误:你当前的卡片模板同时依赖商品信息和对应价格,两个数组是按索引一一对应的关联关系,不能拆分遍历,必须先合并为单组数据再渲染。
正确实现方案

前提约定:后端返回的data.Products和data.Prices数组长度一致、索引一一对应(即Products第i项的商品,对应Prices第i项的价格,这是这类拆分返回接口的常规设计)

基础合并版本(适配当前模板需求)

直接按索引合并两个数组,再遍历渲染:

const displayProducts = (data) => {
  const { Products, Prices } = data;
  // 按索引合并商品信息和对应价格
  const mergedProductList = Products.map((productItem, index) => {
    return {
      ...productItem, // 保留商品原有的所有字段
      Price: Prices[index] // 取对应索引的价格值
    }
  })

  // 遍历合并后的数据生成HTML
  const htmlString = mergedProductList
    .map((item) => {
      return `<div class="products">
        <h2>${item.ProductType}<span class="span-available">.${item.ProductDescription}</span></h2>
        <div class="products-right-wrapper">
          <div class="products-price-wrapper">
            <div class="products-price-container">
                <sub class="discount-price">$17.99</sub>
                <p>${item.Price}</p>
            </div>
          </div>
        </div>
      </div>`;
    })
    .join('');

  productList.innerHTML = htmlString;
}

容错升级版本

如果存在部分商品没有对应价格、两个数组长度不一致的情况,可增加兜底逻辑避免渲染异常:

const displayProducts = (data) => {
  const { Products, Prices = [] } = data;
  const mergedProductList = Products.map((productItem, index) => {
    return {
      ...productItem,
      // 无对应价格时显示兜底文案
      Price: Prices[index] ?? '暂无报价'
    }
  })

  // 后续渲染逻辑和上方基础版本一致
  const htmlString = mergedProductList.map(item => /* 同基础版本的模板逻辑 */).join('');
  productList.innerHTML = htmlString;
}

分开展示场景适配

如果你的需求不是合并成单个商品卡片,而是要分别展示两个数组的全部内容,可拆分两次遍历拼接HTML:

const displayProducts = (data) => {
  // 遍历商品数组生成对应片段
  const productsFragment = data.Products.map(item => `<div>商品:${item.ProductType} ${item.ProductDescription}</div>`).join('');
  // 遍历价格数组生成对应片段
  const pricesFragment = data.Prices.map(priceItem => `<div>商品价格:${priceItem.Price}</div>`).join('');
  
  productList.innerHTML = productsFragment + pricesFragment;
}

内容的提问来源于stack exchange,提问作者C0de Cisco

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.02 06:36:04