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:13

Recursive, standalone function which can return any number of items (identical to lodash.sampleSize):

function getRandomElementsFromArray(array, numberOfRandomElementsToExtract = 1) {
    const elements = [];

    function getRandomElement(arr) {
        if (elements.length < numberOfRandomElementsToExtract) {
            const index = Math.floor(Math.random() * arr.length)
            const element = arr.splice(index, 1)[0];

            elements.push(element)

            return getRandomElement(arr)
        } else {
            return elements
        }
    }

    return getRandomElement([...array])
}
查看更多
君临天下
3楼-- · 2018-12-31 01:15

Prototype Method

If you plan on getting a random value a lot, you might want to define a function for it.

First, put this in your code somewhere:

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

Now:

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

Code released into the public domain under the terms of the CC0 1.0 license.

查看更多
孤独寂梦人
4楼-- · 2018-12-31 01:15

Editing Array prototype can be harmful. Here it is a simple function to do the job.

function getArrayRandomElement (arr) {
  if (arr && arr.length) {
    return arr[Math.floor(Math.random() * arr.length)];
  }
  // The undefined will be returned if the empty array was passed
}

Usage:

// Example 1
var item = getArrayRandomElement(['January', 'February', 'March']);

// Example 2
var myArray = ['January', 'February', 'March'];
var item = getArrayRandomElement(myArray);
查看更多
伤终究还是伤i
5楼-- · 2018-12-31 01:15

Here is an example of how to do it:

$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)];
查看更多
临风纵饮
6楼-- · 2018-12-31 01:16

If you've already got underscore or lodash included in your project you can use _.sample.

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

If you need to get more than one item randomly, you can pass that as a second argument in underscore:

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

or use the _.sampleSize method in lodash:

// will return two items randomly from the array using lodash
_.sampleSize(['January', 'February', 'March'], 2);
查看更多
骚的不知所云
7楼-- · 2018-12-31 01:16

Say you want to choose a random item that is different from the last time (not really random, but still a common requirement)...

Building upon the answer by @Markus, we can add another prototype 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];
   }
}

And implement like so:

var myRandomDiffElement = myArray.randomDiffElement(lastRandomElement)
查看更多
登录 后发表回答