JavaScript 中随机选择元素的函数


假设我们有一个不包含重复元素的字面量的数组,如下所示 −

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 ]

更新于: 2020 年 10 月 21 日

111 次浏览

开创你的 职业生涯

完成本课程后获得认证

开始学习
广告
© . All rights reserved.