这个例子涵盖了如何在javascript中从一个数组中获得一个随机数。
让我们声明一个数组
var array = [1,2,3,4]
这里的元素索引从0开始,结束索引是array.length-1,即1。
Javascript从数组中获取随机数的例子
我们有多种方法可以做到
- 使用Math.random()函数
Math.random()生成0到1之间的随机数,并与数组长度相乘,数字总是在0到数组长度之间返回,这被称为随机指数。Math.floor(),对于浮动的下限值返回整数。
var array = [1,2,3,4]
let randomIndex=Math.floor(Math.random()*array.length);
var randomNumber = array[randomIndex];
console.log(randomNumber); // returns 1 or 2 or 3 or 4
- 使用Lodash或underscore示例函数
sample() 在Lodash/underscore中的函数为一个给定的项目列表返回随机数。
语法:
_.sample(list, [Optional Count])
List 是一个数组或集合 - 返回的随机数的数量,可选,默认是1Optional Count
下面是一个例子
var array = [1,2,3,4]
console.log(_.sample(array)); // returns 1 or 2 or 3 or 4
console.log(_.sample(array,3)); // returns array of three random numbers
另一个函数,lodash中的sampleSize() ,也是做同样的事情。
var array = [1,2,3,4]
console.log(_.sampleSize(array)); // returns 1 or 2 or 3 or 4
console.log(_.sampleSize(array,3)); // returns array of three random numbers
结语
最后,学习如何在javascript中从一个数组中获得随机数。