返回范围内的 5 个随机数,第一个数字不能为零 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/31 22:36:17

我们需要编写一个 JavaScript 函数,生成一个恰好包含五个唯一随机数的数组。条件是所有数字都必须在 [0, 9] 范围内,并且第一个数字不能为 0。

示例

以下是代码 −

const fiveRandoms = () => {
   const arr = []
   while (arr.length < 5) {
      const random = Math.floor(Math.random() * 10);
      if (arr.indexOf(random) > -1){
         continue;
      };
      if(!arr.length && !random){
         continue;
      }
      arr[arr.length] = random;
   }
   return arr;
};
console.log(fiveRandoms());

输出

这将在控制台中产生以下输出 −

[ 9, 0, 8, 5, 4 ]

相关文章


有用资源