考虑:

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

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


当前回答

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

其他回答

为了寻找一句真正的俏皮话,我得出了这个结论:

['January', 'February', 'March'].reduce((a, c, i, o) => { return o[Math.floor(Math.random() * Math.floor(o.length))]; })

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(“项目:”,项目);

这与@Jacob Relkin的解决方案类似,但更普遍:

这是ES2015:

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

该代码的工作原理是在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)];

如果你想把它写在一行上,就像Pascual的解决方案一样,另一个解决方案是使用ES6的find函数来写它(基于这样一个事实,从n个项目中随机选择一个的概率是1/n):

var item = ['A', 'B', 'C', 'D']。找到((_,我,ar) = > math . random () < 1 / (ar.length - i)); console.log(项);

如果有充分的理由不将数组保存在单独的变量中,可以将该方法用于测试目的。否则,其他答案(地板(随机()*长度和使用一个单独的函数)是你的方式。