考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
当前回答
如果你想把它写在一行上,就像Pascual的解决方案一样,另一个解决方案是使用ES6的find函数来写它(基于这样一个事实,从n个项目中随机选择一个的概率是1/n):
var item = ['A', 'B', 'C', 'D']。找到((_,我,ar) = > math . random () < 1 / (ar.length - i)); console.log(项);
如果有充分的理由不将数组保存在单独的变量中,可以将该方法用于测试目的。否则,其他答案(地板(随机()*长度和使用一个单独的函数)是你的方式。
其他回答
如果你的项目中已经包含了下划线或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);
要获得加密强随机项形式数组使用
let rndItem = a=> a[rnd()*a.length|0]; 令RND = ()=> crypto。getRandomValues(新Uint32Array (1) [0] / 2 * * 32; var myArray = ['January', 'February', 'March']; log(rndItem(myArray))
如果您有固定的值(如月份名称列表),并且想要一行解决方案
var result = ['January', 'February', 'March'][Math.floor(Math.random() * 3)]
数组的第二部分是一个访问操作,如在JavaScript中为什么[5,6,8,7][1,2]= 8所描述的那样?
如果你需要多次获取一个随机项,那么,显然你会使用函数。一种方法是使该函数成为Array的方法。原型,但这通常会让你因为篡改内置原型而被大声斥责。
但是,你可以将方法添加到特定的数组本身:
var months = ['January', 'February', 'March'];
months.random = function() {
return this[Math.floor(Math.random()*this.length)];
};
这样你就可以随心所欲地使用months.random(),而不会干扰通用的Array.prototype。
与任何随机函数一样,你会冒着连续得到相同值的风险。如果你不想这样做,你需要用另一个属性跟踪之前的值:
months.random=function() {
var random;
while((random=this[Math.floor(Math.random()*this.length)]) == this.previous);
this.previous=random;
return random;
};
如果你要经常做这样的事情,你不想篡改Array。原型,你可以这样做:
function randomValue() {
return this[Math.floor(Math.random()*this.length)];
}
var data = [ … ];
var moreData = [ … ];
data.random=randomValue;
moreData.random=randomValue;
获取随机元素的通用方法:
让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; }