Sar*_*rah 714 javascript
考虑:
var myArray = ['January', 'February', 'March'];
Run Code Online (Sandbox Code Playgroud)
如何使用JavaScript从此数组中选择随机值?
Jac*_*kin 1340
var rand = myArray[Math.floor(Math.random() * myArray.length)];
Run Code Online (Sandbox Code Playgroud)
Mar*_*son 85
我发现将原型函数添加到Array类更简单:
Array.prototype.randomElement = function () {
return this[Math.floor(Math.random() * this.length)]
}
Run Code Online (Sandbox Code Playgroud)
现在我只需键入以下内容即可获得随机数组元素:
var myRandomElement = myArray.randomElement()
Run Code Online (Sandbox Code Playgroud)
请注意,这将为所有数组添加一个属性,因此如果您使用循环使用for..in,则应使用.hasOwnProperty():
for (var prop in myArray) {
if (myArray.hasOwnProperty(prop)) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
(这对你来说可能是也可能不是麻烦.)
Bre*_*Nee 64
如果您已经在项目中包含下划线或lodash,则可以使用_.sample.
// will return one item randomly from the array
_.sample(['January', 'February', 'March']);
Run Code Online (Sandbox Code Playgroud)
如果您需要随机获得多个项目,可以将其作为下划线中的第二个参数传递:
// will return two items randomly from the array using underscore
_.sample(['January', 'February', 'March'], 2);
Run Code Online (Sandbox Code Playgroud)
或者使用_.sampleSizelodash中的方法:
// will return two items randomly from the array using lodash
_.sampleSize(['January', 'February', 'March'], 2);
Run Code Online (Sandbox Code Playgroud)
Ben*_*bin 19
如果您计划大量获取随机值,则可能需要为其定义函数.
首先,将它放在代码中的某处:
Array.prototype.sample = function(){
return this[Math.floor(Math.random()*this.length)];
}
Run Code Online (Sandbox Code Playgroud)
现在:
[1,2,3,4].sample() //=> a random element
Run Code Online (Sandbox Code Playgroud)
代码根据CC0 1.0许可条款发布到公共领域.
Cra*_*Tim 17
假设你想选择一个与上次不同的随机项目(不是真正随机的,但仍然是一个常见的要求)......
在@Markus的答案基础上,我们可以添加另一个原型函数:
Array.prototype.randomDiffElement = function(last) {
if (this.length == 0) {
return;
} else if (this.length == 1) {
return this[0];
} else {
var num = 0;
do {
num = Math.floor(Math.random() * this.length);
} while (this[num] == last);
return this[num];
}
}
Run Code Online (Sandbox Code Playgroud)
并执行如下:
var myRandomDiffElement = myArray.randomDiffElement(lastRandomElement)
Run Code Online (Sandbox Code Playgroud)
Ank*_*oni 14
~~速度要快得多Math.Floor(),因此在使用UI元素生成输出时进行性能优化,~~赢得游戏.更多信息
var rand = myArray[~~(Math.random() * myArray.length)];
Run Code Online (Sandbox Code Playgroud)
但是,如果你知道数组将有比你想要在Bitwise运算符之间重新考虑的数百万个元素,并且Math.Floor()因为按位运算符在大数字上表现得很奇怪.请参阅以下使用输出解释的示例.更多信息
var number = Math.floor(14444323231.2); // => 14444323231
var number = 14444323231.2 | 0; // => 1559421343
Run Code Online (Sandbox Code Playgroud)
Ton*_*gan 14
许多提供的解决方案都向特定数组添加了一个方法,这限制了它只能用于该数组。该解决方案是可重用的代码,适用于任何数组,并且可以确保类型安全。
export function randChoice<T>(arr: Array<T>): T {
return arr[Math.floor(Math.random() * arr.length)]
}
Run Code Online (Sandbox Code Playgroud)
function randChoice(arr) {
return arr[Math.floor(Math.random() * arr.length)]
}
Run Code Online (Sandbox Code Playgroud)
fox*_*ris 10
最短的版本:
var myArray = ['January', 'February', 'March'];
var rand = myArray[(Math.random() * myArray.length) | 0]
Run Code Online (Sandbox Code Playgroud)
Ste*_*han 10
如果你想把它写在一行上,比如 Pascual 的解决方案,另一种解决方案是使用 ES6 的 find 函数编写它(基于这样一个事实,从n项目中随机选择一个的概率是1/n):
var item = ['A', 'B', 'C', 'D'].find((_, i, ar) => Math.random() < 1 / (ar.length - i));
console.log(item);Run Code Online (Sandbox Code Playgroud)
将该方法用于测试目的,如果有充分的理由不将数组仅保存在单独的变量中。否则其他答案(floor(random()*length并使用单独的函数)是您要走的路。
如果您有固定值(如月份名称列表)并想要一个单行解决方案
var result = ['January', 'February', 'March'][Math.floor(Math.random() * 3)]
Run Code Online (Sandbox Code Playgroud)
数组的第二部分是一个访问操作,如JavaScript中的为什么[5,6,8,7] [1,2] = 8?
如果您需要多次获取随机项目,那么显然您会使用函数。一种方法是使该函数成为 的方法Array.prototype,但这通常会让您因篡改内置原型而受到谴责。
但是,您可以将该方法添加到特定数组本身:
\nvar months = [\'January\', \'February\', \'March\'];\nmonths.random = function() {\n return this[Math.floor(Math.random()*this.length)];\n};\nRun Code Online (Sandbox Code Playgroud)\n这样您就可以months.random()随意使用,而不会干扰通用的Array.prototype.
与任何随机函数一样,您面临着连续获得相同值的风险。如果您不想\xe2\x80\x99 那样,您将需要使用另一个属性跟踪先前的值:
\nmonths.random=function() {\n var random;\n while((random=this[Math.floor(Math.random()*this.length)]) == this.previous);\n this.previous=random;\n return random;\n};\nRun Code Online (Sandbox Code Playgroud)\n如果你经常做这种事情,并且你不想篡改Array.prototype,你可以这样做:
function randomValue() {\n return this[Math.floor(Math.random()*this.length)];\n}\n\nvar data = [ \xe2\x80\xa6 ];\nvar moreData = [ \xe2\x80\xa6 ];\n\ndata.random=randomValue;\nmoreData.random=randomValue;\nRun Code Online (Sandbox Code Playgroud)\n
编辑数组原型可能有害。这是一个简单的功能来完成这项工作。
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
}
Run Code Online (Sandbox Code Playgroud)
用法:
// Example 1
var item = getArrayRandomElement(['January', 'February', 'March']);
// Example 2
var myArray = ['January', 'February', 'March'];
var item = getArrayRandomElement(myArray);
Run Code Online (Sandbox Code Playgroud)
Faker.js具有许多实用程序功能,用于生成随机测试数据。在测试套件的上下文中,这是一个不错的选择:
const Faker = require('faker');
Faker.random.arrayElement(['January', 'February', 'March']);
Run Code Online (Sandbox Code Playgroud)
正如评论者提到的那样,通常不应在生产代码中使用此库。
要获得加密强度强的随机项形式数组,请使用
let rndItem = a=> a[rnd()*a.length|0];
let rnd = ()=> crypto.getRandomValues(new Uint32Array(1))[0]/2**32;
var myArray = ['January', 'February', 'March'];
console.log( rndItem(myArray) )Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
452609 次 |
| 最近记录: |