考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
当前回答
获取随机元素的通用方法:
让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; }
其他回答
在我看来,与其把原型搞得乱七八糟,或者及时声明,我更喜欢把它暴露在窗口:
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)循环
我找到了一种方法来解决顶部答案的复杂性,只需将变量rand连接到另一个变量,允许该数字在myArray[];的调用中显示。通过删除创建的新数组并处理它的复杂性,我提出了一个可行的解决方案:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myArray = ['January', 'February', 'March', 'April', 'May'];
var rand = Math.floor(Math.random() * myArray.length);
var concat = myArray[rand];
function random() {
document.getElementById("demo").innerHTML = (concat);
}
</script>
<button onClick="random();">
Working Random Array generator
</button>
</body>
</html>
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(“项目:”,项目);
~~比Math.Floor()快得多,所以当涉及到使用UI元素生成输出的性能优化时,~~赢得了比赛。更多信息
var rand = myArray[~~(Math.random() * myArray.length)];
但是,如果您知道数组将有数百万个元素,那么您可能需要在位操作符和Math.Floor()之间重新考虑,因为位操作符对大数字的表现很奇怪。请参阅下面的输出示例。
var number = Math.floor(14444323231.2); // => 14444323231
var number = 14444323231.2 | 0; // => 1559421343
如果你的项目中已经包含了下划线或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);