返回 5 個範圍內的隨機數,第一個數字不能為零 - JavaScript


我們需要編寫一個 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 ]

更新於:30-Sep-2020

119 次瀏覽

開啟您的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.