考虑:

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

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


当前回答

简单功能:

var myArray = ['January', 'February', 'March'];
function random(array) {
     return array[Math.floor(Math.random() * array.length)]
}
random(myArray);

OR

var myArray = ['January', 'February', 'March'];
function random() {
     return myArray[Math.floor(Math.random() * myArray.length)]
}
random();

OR

var myArray = ['January', 'February', 'March'];
function random() {
     return myArray[Math.floor(Math.random() * myArray.length)]
}
random();

其他回答

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

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

我真的很惊讶没有人尝试使用本机随机值:

array[Date.now()%array.length]

对于长度超过160000000000的数组,它将不起作用,但我相信您永远不会创建这样的数组

UPD

至于你的问题是如何从名为myArray的数组中选择随机值(与len=3),解决方案应该是:

myArray[Date.now()%myArray.length]

Faker.js有许多生成随机测试数据的实用函数。在测试套件的上下文中,这是一个很好的选择:

const faker = require('faker');
faker.helpers.arrayElement(['January', 'February', 'March']);

正如评论者所提到的,您通常不应该在产品代码中使用这个库。

Randojs使这更简单和可读:

console.log(rando(['January', 'February', 'March'])。值); < script src = " https://randojs.com/1.0.0.js " > < /脚本>

最短的版本: var myArray = ['January', 'February', 'March']; var rand = myArray[(Math.random() * myArray.length) | 0] console.log (rand)