JavaScript - 如何从数组中随机选取元素?
javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/30 9:16:17
假设我们有一个不包含重复元素的文字数组,例如 −
const arr = [2, 5, 4, 45, 32, 46, 78, 87, 98, 56, 23, 12];
我们需要编写一个 JavaScript 函数,该函数接受一个唯一文字数组和一个数字 n。
该函数应返回一个包含 n 个元素的数组,这些元素均从输入数组中随机选择,并且任何元素在输出数组中都不应出现超过一次。
示例
以下是代码 −
const arr = [2, 5, 4, 45, 32, 46, 78, 87, 98, 56, 23, 12];
const chooseRandom = (arr, num = 1) => {
const res = [];
for(let i = 0; i < num; ){
const random = Math.floor(Math.random() * arr.length);
if(res.indexOf(arr[random]) !== -1){
continue;
};
res.push(arr[random]);
i++;
};
return res;
};
console.log(chooseRandom(arr, 4));
输出
这将在控制台中产生以下输出 −
[ 5, 2, 4, 78 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

