考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
当前回答
我真的很惊讶没有人尝试使用本机随机值:
array[Date.now()%array.length]
对于长度超过160000000000的数组,它将不起作用,但我相信您永远不会创建这样的数组
UPD
至于你的问题是如何从名为myArray的数组中选择随机值(与len=3),解决方案应该是:
myArray[Date.now()%myArray.length]
其他回答
在我看来,与其把原型搞得乱七八糟,或者及时声明,我更喜欢把它暴露在窗口:
window.choice = function() {
if (!this.length || this.length == 0) return;
if (this.length == 1) return this[0];
return this[Math.floor(Math.random()*this.length)];
}
现在,在你的应用程序的任何地方,你可以这样称呼它:
var rand = window.choice.call(array)
这样你仍然可以正确地使用for(x in array)循环
如果你的项目中已经包含了下划线或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[Date.now()%array.length]
对于长度超过160000000000的数组,它将不起作用,但我相信您永远不会创建这样的数组
UPD
至于你的问题是如何从名为myArray的数组中选择随机值(与len=3),解决方案应该是:
myArray[Date.now()%myArray.length]
通过在数组原型上增加一个方法,可以方便地获取随机值。
在本例中,您可以从数组中获取单个或多个随机值。
您可以通过单击代码片段按钮运行以测试代码。
Array.prototype.random = function(n){ if(n&&n>1){ const a = []; for(let i = 0;i<n;i++){ a.push(this[Math.floor(Math.random()*this.length)]); } return a; } else { return this[Math.floor(Math.random()*this.length)]; } } const mySampleArray = ['a','b','c','d','e','f','g','h']; mySampleArray.random(); // return any random value etc. 'a', 'b' mySampleArray.random(3); //retun an array with random values etc: ['b','f','a'] , ['d','b','d'] alert(mySampleArray.random()); alert(mySampleArray.random(3));
获取随机元素的通用方法:
让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; }