在JS中如何从给定数组中随机抽取指定长度的新数组?
实现方案
完全可以借助Math.random实现该需求,以下是两种常见场景的代码实现:
- 场景1:允许抽取的元素重复
// 生成1-50的原始数组 const array1 = Array.from({length: 50}, (_, index) => index + 1); const targetLength = 5; const randomizedArray = []; for (let i = 0; i < targetLength; i++) { // 生成合法的随机索引 const randomIndex = Math.floor(Math.random() * array1.length); randomizedArray.push(array1[randomIndex]); } console.log(randomizedArray);
- 场景2:要求抽取的元素不重复(绝大多数场景的需求)
推荐用Fisher-Yates洗牌算法实现,效率更高且随机性均匀:
const array1 = Array.from({length: 50}, (_, index) => index + 1); const targetLength = 5; // 拷贝原数组后打乱,避免修改原始数据 const shuffledArr = [...array1]; for (let i = shuffledArr.length - 1; i > 0; i--) { const randomIndex = Math.floor(Math.random() * (i + 1)); // 交换元素位置 [shuffledArr[i], shuffledArr[randomIndex]] = [shuffledArr[randomIndex], shuffledArr[i]]; } // 截取前N位作为结果 const randomizedArray = shuffledArr.slice(0, targetLength); console.log(randomizedArray);
Math.random会返回[0, 1)区间的伪随机浮点数,乘以数组长度后取整即可得到合法的数组下标,是这类随机抽取需求的通用实现基础。
内容的提问来源于stack exchange,提问作者optionalfigure
相关产品推荐
相关产品推荐

