返回 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 ]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP