生成一個可在 JavaScript 中被 n 整除的隨機數
我們需要編寫一個 JavaScript 函式,它將一個數字作為唯一的引數。然後函式應該返回一個隨機生成的數字,該數字始終可以被引數提供的數字整除。
示例
程式碼如下:
const num = 21; // function that generates random numbers divisible by n with a default upper limit of 1000000 const specialRandom = (num = 1, limit = 1000000) => { // getting a random number const random = Math.random() * limit; // rounding it off to be divisible by num const res = Math.round( random / num ) * num; return res; }; console.log(specialRandom(num));
輸出
而在控制檯中輸出內容如下:
6006
此輸出每次執行都可能不同。
廣告