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

JavaScript按指定次数重复数组元素生成新数组的方法求助

解决数组元素按指定次数重复生成新数组的问题

这里给你两种简单直接的JavaScript实现方案:

方法一:map + flat 组合

利用Array.map生成对应重复次数的子数组,再用flat()将二维数组拍平为一维:

const a = [1, 2, 3, 2];
const b = ['this', 'is', 'my', 'good example'];

const c = a.map((count, index) => Array(count).fill(b[index])).flat();
console.log(c); // 输出:['this', 'is', 'is', 'my', 'my', 'my', 'good example', 'good example']

原理:每个a[i]对应生成一个长度为a[i]的数组,数组里的元素全是b[i],最后通过flat()把嵌套的数组展开成最终结果。

方法二:reduce 累加

如果不想用flat(),可以用Array.reduce循环累加元素:

const a = [1, 2, 3, 2];
const b = ['this', 'is', 'my', 'good example'];

const c = a.reduce((result, count, index) => {
  for (let i = 0; i < count; i++) {
    result.push(b[index]);
  }
  return result;
}, []);
console.log(c); // 同样得到目标数组

原理:以空数组为初始值,遍历a时根据当前的重复次数,把对应的b元素多次推入结果数组。

另外说下你提到的String.repeat——这个方法是用来重复字符串内容的,比如'is'.repeat(2)会得到'isis',而不是两个独立的'is'元素,所以它并不适用于生成数组元素重复的场景,建议用上面的数组操作方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 16:12:05