考虑:

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

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


当前回答

最短的版本: var myArray = ['January', 'February', 'March']; var rand = myArray[(Math.random() * myArray.length) | 0] console.log (rand)

其他回答

简单功能:

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();

通过在数组原型上增加一个方法,可以方便地获取随机值。

在本例中,您可以从数组中获取单个或多个随机值。

您可以通过单击代码片段按钮运行以测试代码。

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));

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

请尝试以下代码..

//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);

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许可证的条款将这些代码片段发布到公共领域。