在 JavaScript 中生成可被 n 整除的随机数
javascriptweb developmentfront end technologyobject oriented programming
我们需要编写一个 JavaScript 函数,该函数将数字作为唯一参数。然后,该函数应返回一个随机生成的数字,该数字始终可被参数提供的数字整除。
示例
其代码为 −
const num = 21;
// 生成可被 n 整除的随机数的函数,默认上限为 1000000
const specialRandom = (num = 1, limit = 1000000) => {
// 获取随机数
const random = Math.random() * limit;
// 四舍五入为可被 num 整除
const res = Math.round( random / num ) * num;
return res;
};
console.log(specialRandom(num));
输出
控制台中的输出将是 −
6006
此输出在每次运行时可能会有所不同。
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

