考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
当前回答
最短的版本: var myArray = ['January', 'February', 'March']; var rand = myArray[(Math.random() * myArray.length) | 0] console.log (rand)
其他回答
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(“项目:”,项目);
我真的很惊讶没有人尝试使用本机随机值:
array[Date.now()%array.length]
对于长度超过160000000000的数组,它将不起作用,但我相信您永远不会创建这样的数组
UPD
至于你的问题是如何从名为myArray的数组中选择随机值(与len=3),解决方案应该是:
myArray[Date.now()%myArray.length]
下面是一个如何做到这一点的例子:
$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)];
如果你的项目中已经包含了下划线或lodash,你可以使用_.sample。
// will return one item randomly from the array
_.sample(['January', 'February', 'March']);
如果你需要随机获取一个以上的项,你可以将它作为第二个参数在下划线中传递:
// will return two items randomly from the array using underscore
_.sample(['January', 'February', 'March'], 2);
或者使用_。lodash中的sampleSize方法:
// will return two items randomly from the array using lodash
_.sampleSize(['January', 'February', 'March'], 2);
编辑Array原型可能有害。这里是一个简单的函数来完成这项工作。
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
}
用法:
// Example 1
var item = getArrayRandomElement(['January', 'February', 'March']);
// Example 2
var myArray = ['January', 'February', 'March'];
var item = getArrayRandomElement(myArray);