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

如何将数组在自身内重复指定x次?publicKey数组重复实现求助

解决JavaScript数组重复x次的问题

嘿,我懂你碰到的麻烦了——在JavaScript里直接用publicKey * x确实没法得到重复的数组,因为数组和数字相乘会触发类型转换,最后得到的要么是NaN要么完全不是你想要的结果。下面给你几个简单有效的解决方案,完全匹配你的需求:

方法1:用Array.from + flat()(简洁推荐)

一行代码就能搞定,可读性也拉满:

const publicKey = [76, 152, 93, 102, 145, 181];
const repeatCount = 3;
const repeatedArray = Array.from({ length: repeatCount }, () => [...publicKey]).flat();

console.log(repeatedArray);
// 输出:[76, 152, 93, 102, 145, 181, 76, 152, 93, 102, 145, 181, 76, 152, 93, 102, 145, 181]
  • Array.from({ length: repeatCount }) 创建一个长度为repeatCount的空数组
  • 第二个参数是映射函数,每个位置都返回原数组的副本(用[...publicKey]避免引用关联问题)
  • 最后用flat()把二维数组“拍平”成一维数组

方法2:循环拼接(直观易懂)

如果喜欢更直白的写法,用循环+concat()也很靠谱:

const publicKey = [76, 152, 93, 102, 145, 181];
const repeatCount = 3;
let repeatedArray = [];

for (let i = 0; i < repeatCount; i++) {
  repeatedArray = repeatedArray.concat(publicKey);
}

console.log(repeatedArray);
// 同样得到预期结果

原理超简单:每次循环都把原数组拼接到结果数组里,循环多少次就重复多少次。

方法3:用Array.fill() + flat()

这也是一种简洁的写法,和方法1异曲同工:

const publicKey = [76, 152, 93, 102, 145, 181];
const repeatCount = 3;
const repeatedArray = Array(repeatCount).fill([...publicKey]).flat();

console.log(repeatedArray);
  • Array(repeatCount).fill([...publicKey]) 创建一个包含repeatCount个原数组副本的数组
  • 再用flat()转成一维数组

注意:这里一定要用[...publicKey]复制原数组,如果直接写fill(publicKey),数组里的所有元素都会指向同一个原数组的引用(如果原数组是引用类型会出问题,你的例子是基本类型虽能工作,但养成复制习惯更安全)。

内容的提问来源于stack exchange,提问作者Mārtiņš Ciekurs

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:25:47