如何在javascript中从一个数组中获取随机值

您所在的位置:网站首页 js输出数组的值 如何在javascript中从一个数组中获取随机值

如何在javascript中从一个数组中获取随机值

2024-04-11 03:44| 来源: 网络整理| 查看: 265

这个例子涵盖了如何在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中从一个数组中获得随机数。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3