考虑:

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

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


当前回答

var item = myArray[Math.floor(Math.random()*myArray.length)];

或相当短的版本:

var item = myArray[(Math.random()*myArray.length)|0];

示例代码:

var myArray = ['January', 'February', 'March']; var item = myArray[(Math.random()*myArray.length)|0]; console.log(“项目:”,项目);

其他回答

您可以考虑在Array原型上定义一个函数,以便创建一个返回随机元素的方法[].sample()。

首先,要定义原型函数,将以下代码片段放入代码中:

Array.prototype.sample = function(){
  return this[Math.floor(Math.random()*this.length)];
}

之后,要从数组中随机抽取一个元素,只需调用.sample():

[1,2,3,4].sample() //=> a random element

我将根据CC0 1.0许可证的条款将这些代码片段发布到公共领域。

如果你的项目中已经包含了下划线或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);

创建一个随机值并传递给数组

请尝试以下代码..

//For Search textbox random value
var myPlaceHolderArray = ['Hotels in New York...', 'Hotels in San Francisco...', 'Hotels Near Disney World...', 'Hotels in Atlanta...'];
var rand = Math.floor(Math.random() * myPlaceHolderArray.length);
var Placeholdervalue = myPlaceHolderArray[rand];

alert(Placeholdervalue);

~~比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

这是一个简单的一行代码:

const randomElement = array[Math.floor(Math.random() * array.length)];

例如:

const月=(“1”,“2”,“3”、“4”,“可能”,“6”,“7”); const random = Math.floor(Math.random() * months.length); console.log(随机、几个月(随机));