使用JavaScript生成一組範圍內的n個隨機數
我們需要編寫一個JavaScript函式,該函式接受一個數字(比如n)和一個由兩個數字組成的陣列,該陣列表示一個範圍。該函式應該返回n個隨機元素陣列,這些元素都介於第二個引數提供的範圍內。
示例
以下是程式碼 -
const num = 10;
const range = [5, 15];
const randomBetween = (a, b) => {
return ((Math.random() * (b - a)) + a).toFixed(2);
};
const randomBetweenRange = (num, range) => {
const res = [];
for(let i = 0; i < num; ){
const random = randomBetween(range[0], range[1]);
if(!res.includes(random)){
res.push(random);
i++;
};
};
return res;
};
console.log(randomBetweenRange(num, range));輸出
它將在控制檯中生成以下輸出 -
[ '13.25', '10.31', '11.83', '5.25', '6.28', '9.99', '6.09', '7.58', '12.64', '8.92' ]
這只是許多可能的輸出之一。
讓我們再次執行它以獲得不同的隨機輸出 -
[ '5.29', '7.95', '11.61', '7.83', '10.56', '7.48', '12.96', '6.92', '8.98', '9.43' ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP