考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
当前回答
下面是一个如何做到这一点的例子:
$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)];
其他回答
创建一个随机值并传递给数组
请尝试以下代码..
//For Search textbox random value
var myPlaceHolderArray = ['Hotels in New York...', 'Hotels in San Francisco...', 'Hotels Near Disney World...', 'Hotels in Atlanta...'];
var rand = Math.floor(Math.random() * myPlaceHolderArray.length);
var Placeholdervalue = myPlaceHolderArray[rand];
alert(Placeholdervalue);
简单功能:
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();
如果你想把它写在一行上,就像Pascual的解决方案一样,另一个解决方案是使用ES6的find函数来写它(基于这样一个事实,从n个项目中随机选择一个的概率是1/n):
var item = ['A', 'B', 'C', 'D']。找到((_,我,ar) = > math . random () < 1 / (ar.length - i)); console.log(项);
如果有充分的理由不将数组保存在单独的变量中,可以将该方法用于测试目的。否则,其他答案(地板(随机()*长度和使用一个单独的函数)是你的方式。
获取随机元素的通用方法:
让some_array =[‘简’,2月,3月,4月,“可能”); Let months = random_elems(some_array, 3); console.log(个月); 函数random_elems(arr, count) { 让len = arrr .length; 让查找= {}; Let TMP = []; If (count > len) Count = len; 对于(设I = 0;I < count;我+ +){ 让指数; {做 index = ~~(Math.random() * len); } while(查找中的索引); 查找[index] = null; tmp.push (arr(指数)); } 返回tmp; }
如果您有固定的值(如月份名称列表),并且想要一行解决方案
var result = ['January', 'February', 'March'][Math.floor(Math.random() * 3)]
数组的第二部分是一个访问操作,如在JavaScript中为什么[5,6,8,7][1,2]= 8所描述的那样?