从JavaScript数组获取随机值

考虑:

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

我怎样才能使用JavaScript从这个数组中select一个随机值?

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

我发现将一个原型函数添加到Array类更简单:

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

现在我可以通过input以下内容来获得随机数组元素:

 var myRandomElement = myArray.randomElement() 

请注意,这将为所有数组添加一个属性,所以如果你正在循环使用for..in你应该使用.hasOwnProperty()

 for (var prop in myArray) { if (myArray.hasOwnProperty(prop)) { ... } } 

(这可能会也可能不是你的麻烦。)

如果您的项目中包含下划线或lodash ,则可以使用_.sample

 // will return one item randomly from the array _.sample(['January', 'February', 'March']); 

如果您需要随机获取多个项目,则可以将其作为下划线中的第二个parameter passing:

 // will return two items randomly from the array using underscore _.sample(['January', 'February', 'March'], 2); 

或者在_.sampleSize中使用_.sampleSize方法:

 // will return two items randomly from the array using lodash _.sampleSize(['January', 'February', 'March'], 2); 

假设你想select一个与上次不同的随机项目(不是真的随机,但仍然是一个共同的要求)…

基于@Markus的回答,我们可以添加另一个原型function:

 Array.prototype.randomDiffElement = function(last) { if (this.length == 0) { return; } else if (this.length == 1) { return this[0]; } else { var num = 0; do { num = Math.floor(Math.random() * this.length); } while (this[num] == last); return this[num]; } } 

并像这样执行:

 var myRandomDiffElement = myArray.randomDiffElement(lastRandomElement) 

原型方法

如果您计划获得一个随机值,您可能需要为其定义一个函数。

首先,把它放在你的代码中:

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

现在:

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

根据CC0 1.0许可条款发布到公共领域的代码。

如果你有固定的价值(如月份名单),并希望一个单行的解决scheme

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

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

这与@Jacob Relkin的解决scheme相似,但更一般:

这是ES2015:

 const randomChoice = arr => { const randIndex = Math.floor(Math.random() * arr.length); return arr[randIndex]; }; 

代码通过select一个介于0和数组长度之间的随机数字,然后返回该索引处的项目。

我已经find了一个解决最好的答案的复杂的方法,只需将variablesrand连接到另一个variables,该variables允许在myArray [];的调用中显示该数字。 通过删除创build的新数组,并解决它的复杂性,我提出了一个工作解决scheme:

 <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var myArray = ['January', 'February', 'March', 'April', 'May']; var rand = Math.floor(Math.random() * myArray.length); var concat = myArray[rand]; function random() { document.getElementById("demo").innerHTML = (concat); } </script> <button onClick="random();"> Working Random Array generator </button> </body> </html> 

最短的版本:

 var myArray = ['January', 'February', 'March']; var rand = myArray[(Math.random() * myArray.length) | 0] 

这里是一个如何做到这一点的例子:

 $scope.ctx.skills = data.result.skills; $scope.praiseTextArray = [ "Hooray", "You\'re ready to move to a new skill", "Yahoo! You completed a problem", "You\'re doing great", "You succeeded", "That was a brave effort trying new problems", "Your brain was working hard", "All your hard work is paying off", "Very nice job!, Let\'s see what you can do next", "Well done", "That was excellent work", "Awesome job", "You must feel good about doing such a great job", "Right on", "Great thinking", "Wonderful work", "You were right on top of that one", "Beautiful job", "Way to go", "Sensational effort" ]; $scope.praiseTextWord = $scope.praiseTextArray[Math.floor(Math.random()*$scope.praiseTextArray.length)]; 

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

请尝试下面的代码

 //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('item:', item); 

如果你想把它写在一行上,比如Pascual的解决scheme,另一个解决scheme是使用ES6的查找函数来编写它(基于从n项中随机select一个的概率是1/n ):

 var item = ['A', 'B', 'C', 'D'].find((_, i, ar) => Math.random() < 1 / (ar.length - i)); console.log(item); 

在我看来,最好的方式就是搞乱原型,或者及时宣布它,我宁愿把它暴露给窗口:

 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)循环