从JavaScript数组获取随机值

考虑:

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

如何使用JavaScript从此数组中选择随机值?

2020/03/11 11:21:32

这是一个如何做的例子:

$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)];
村村路易2020/03/11 11:21:32

我认为,与其乱搞原型或及时声明它,不如将其暴露在窗口中:

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)正确使用循环

Green老丝Itachi2020/03/11 11:21:32

这类似于@Jacob Relkin的解决方案,但比它更笼统:

这是ES2015:

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

该代码的工作方式是选择一个介于0和数组长度之间的随机数,然后返回该索引处的项目。

阿飞米亚2020/03/11 11:21:32

递归的独立函数,可以返回任意数量的项(与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])
}
十三古一神奇2020/03/11 11:21:32

~~速度比快得多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
Harry泡芙2020/03/11 11:21:32

假设您要选择与上次不同的随机项目(不是随机的,但仍然是常见要求)...

以@Markus的答案为基础,我们可以添加另一个原型函数:

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)
2020/03/11 11:21:32

原型法

如果计划大量获取随机值,则可能需要为其定义一个函数。

首先,将其放在您的代码中:

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

现在:

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

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

Green蛋蛋2020/03/11 11:21:32

这是一个简单的单线

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

const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const randomMonth = months[Math.floor(Math.random() * months.length)];

console.log("random month =>", randomMonth);