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

如何基于JavaScript数组的times属性高效生成迭代子数组?

实现思路与代码示例

需求拆解

遍历head数组的每个元素,根据times属性生成对应数量的子元素:

  • 子元素的headId对应原元素的id,time标记当前是第几次迭代(从1开始)
  • check值结合原元素的norms范围生成,status根据check值与范围的关系分为ok(在范围内)、less(小于最小值)、excess(大于最大值)
  • 子元素的id从1开始连续自增

实现代码

const head = [
  {
    "id": 1,
    "name": "AK47",
    "norms": "15-18",
    "times": 2
  },
  {
    "id": 2,
    "name": "Deagle",
    "norms": "13-21",
    "times": 1
  }
];

// 解析规格范围,生成检查值与对应状态
function getCheckResult(norms) {
  const [min, max] = norms.split('-').map(Number);
  // 扩大随机范围,保证有概率生成不同状态的结果
  const check = Math.floor(Math.random() * (max + 10 - (min - 10))) + (min - 10);
  
  let status;
  if (check < min) status = 'less';
  else if (check > max) status = 'excess';
  else status = 'ok';
  
  return { check, status };
}

// 生成目标数组
let nextId = 1;
const tail = head.flatMap(headItem => {
  // 根据times生成对应数量的子元素
  return Array.from({ length: headItem.times }, (_, idx) => {
    const time = idx + 1;
    const { check, status } = getCheckResult(headItem.norms);
    
    return {
      id: nextId++,
      headId: headItem.id,
      time,
      check,
      status
    };
  });
});

console.log(tail);

代码说明

  1. flatMap的使用:替代map+concat的组合,直接将每个原元素映射为子元素数组并扁平化,代码更简洁高效。
  2. Array.from创建迭代数组:通过指定长度快速生成对应次数的迭代容器,省去手动循环的冗余代码。
  3. 职责分离:将检查值与状态的生成逻辑抽成独立函数getCheckResult,代码更易维护和扩展。
  4. 自增ID维护:用nextId变量统一管理子元素的ID,确保唯一性和连续性。

扩展调整

如果不需要随机生成check值,可以修改getCheckResult函数,比如传入固定值或按特定规则生成(如范围内随机、固定偏移值等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:40:22