Getting a random value from a JavaScript array

2018-12-31 00:34发布

Consider:

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

How can I select a random value from this array using JavaScript?

标签: javascript
23条回答
唯独是你
2楼-- · 2018-12-31 01:16

Create one random value and pass to array

Please try following code..

//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);
查看更多
旧时光的记忆
3楼-- · 2018-12-31 01:17

I've found it even simpler to add a prototype function to the Array class:

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

Now I can get a random array element by just typing:

var myRandomElement = myArray.randomElement()

Note that this will add a property to all arrays, so if you're looping over one using for..in you should use .hasOwnProperty():

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

(That may or may not be a hassle for you.)

查看更多
临风纵饮
4楼-- · 2018-12-31 01:18

The shortest version:

var myArray = ['January', 'February', 'March']; 
var rand = myArray[(Math.random() * myArray.length) | 0]
查看更多
其实,你不懂
5楼-- · 2018-12-31 01:18

In my opinion, better than messing around with prototypes , or declaring it just in time, I prefer exposing it to window:

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

Now anywhere on your app you call it like:

var rand = window.choice.call(array)

This way you can still use for(x in array) loop properly

查看更多
何处买醉
6楼-- · 2018-12-31 01:22

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

or equivalent shorter version:

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

Sample code:

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

查看更多
登录 后发表回答