考虑:

var myArray = ['January', 'February', 'March'];    

如何使用JavaScript从这个数组中选择一个随机值?


当前回答

在我看来,与其把原型搞得乱七八糟,或者及时声明,我更喜欢把它暴露在窗口:

window.choice = function() {
  if (!this.length || this.length == 0) return;
  if (this.length == 1) return this[0];
  return this[Math.floor(Math.random()*this.length)];
}

现在,在你的应用程序的任何地方,你可以这样称呼它:

var rand = window.choice.call(array)

这样你仍然可以正确地使用for(x in array)循环

其他回答

static generateMonth() { const theDate = ['January', 'February', 'March']; const randomNumber = Math.floor(Math.random()*3); 返回theDate [randomNumber]; };

在数组中设置一个常量变量,然后在数组中的三个对象中随机选择另一个常量,然后函数简单地返回结果。

~~比Math.Floor()快得多,所以当涉及到使用UI元素生成输出的性能优化时,~~赢得了比赛。更多信息

var rand = myArray[~~(Math.random() * myArray.length)];

但是,如果您知道数组将有数百万个元素,那么您可能需要在位操作符和Math.Floor()之间重新考虑,因为位操作符对大数字的表现很奇怪。请参阅下面的输出示例。

var number = Math.floor(14444323231.2); // => 14444323231
var number = 14444323231.2 | 0; // => 1559421343

Randojs使这更简单和可读:

console.log(rando(['January', 'February', 'March'])。值); < script src = " https://randojs.com/1.0.0.js " > < /脚本>

如果您有固定的值(如月份名称列表),并且想要一行解决方案

var result = ['January', 'February', 'March'][Math.floor(Math.random() * 3)]

数组的第二部分是一个访问操作,如在JavaScript中为什么[5,6,8,7][1,2]= 8所描述的那样?

简单功能:

var myArray = ['January', 'February', 'March'];
function random(array) {
     return array[Math.floor(Math.random() * array.length)]
}
random(myArray);

OR

var myArray = ['January', 'February', 'March'];
function random() {
     return myArray[Math.floor(Math.random() * myArray.length)]
}
random();

OR

var myArray = ['January', 'February', 'March'];
function random() {
     return myArray[Math.floor(Math.random() * myArray.length)]
}
random();