考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
当前回答
如果你的项目中已经包含了下划线或lodash,你可以使用_.sample。
// will return one item randomly from the array
_.sample(['January', 'February', 'March']);
如果你需要随机获取一个以上的项,你可以将它作为第二个参数在下划线中传递:
// will return two items randomly from the array using underscore
_.sample(['January', 'February', 'March'], 2);
或者使用_。lodash中的sampleSize方法:
// will return two items randomly from the array using lodash
_.sampleSize(['January', 'February', 'March'], 2);
其他回答
如果您有固定的值(如月份名称列表),并且想要一行解决方案
var result = ['January', 'February', 'March'][Math.floor(Math.random() * 3)]
数组的第二部分是一个访问操作,如在JavaScript中为什么[5,6,8,7][1,2]= 8所描述的那样?
方法1:
使用Math.random()函数获取(0- 1,1)之间的随机数 独家)。 将其乘以数组长度得到数字 (0-arrayLength)之间。 使用Math.floor()获取索引范围 从(0到arrayLength-1)。
Const arr = ["foo","bar"]; const randomlyypickedstring =arr[Math.floor(Math.random() * arr.length)]; console.log (randomlyPickedString);
方法2:
random(a, b)方法用于生成(a到b, b不排除)之间的数字。 取下限值,使数字范围从(1到arrayLength)。 减去1得到从(0到arrayLength-1)的下标。
const arr = [“foo”,“bar”]; const randomlyPickedString=arr[Math.floor(random(1, 5))-1]; console.log(randomlyPickedString);
最短的版本: var myArray = ['January', 'February', 'March']; var rand = myArray[(Math.random() * myArray.length) | 0] console.log (rand)
通过在数组原型上增加一个方法,可以方便地获取随机值。
在本例中,您可以从数组中获取单个或多个随机值。
您可以通过单击代码片段按钮运行以测试代码。
Array.prototype.random = function(n){ if(n&&n>1){ const a = []; for(let i = 0;i<n;i++){ a.push(this[Math.floor(Math.random()*this.length)]); } return a; } else { return this[Math.floor(Math.random()*this.length)]; } } const mySampleArray = ['a','b','c','d','e','f','g','h']; mySampleArray.random(); // return any random value etc. 'a', 'b' mySampleArray.random(3); //retun an array with random values etc: ['b','f','a'] , ['d','b','d'] alert(mySampleArray.random()); alert(mySampleArray.random(3));
static generateMonth() { const theDate = ['January', 'February', 'March']; const randomNumber = Math.floor(Math.random()*3); 返回theDate [randomNumber]; };
在数组中设置一个常量变量,然后在数组中的三个对象中随机选择另一个常量,然后函数简单地返回结果。