考虑以下内容:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从该数组中随机选择一个值?
考虑以下内容:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从该数组中随机选择一个值?
这是一个简单的一行代码:
const randomElement = array[Math.floor(Math.random() * array.length)];
const months = ["January", "February", "March", "April", "May", "June", "July"];
const random = Math.floor(Math.random() * months.length);
console.log(random, months[random]);
如果您的项目中已经包含了underscore或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);
_.sampleSize
方法:// will return two items randomly from the array using lodash
_.sampleSize(['January', 'February', 'March'], 2);
你可以考虑在数组原型上定义一个函数,以便创建一个方法 [].sample()
,该方法返回一个随机元素。
首先,在你的代码中插入以下代码片段来定义原型函数:
Array.prototype.sample = function(){
return this[Math.floor(Math.random()*this.length)];
}
然后,要从数组中随机抽取一个元素,只需调用.sample()
:
[1,2,3,4].sample() //=> a random element
我将这些代码片段发布到公共领域,在 CC0 1.0 许可证 的条款下。
.sample()
方法来获取一个随机项。 - Ben Aubin~~
比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
Math.floor
更多。 - alistair~
是按位取反运算符,它可以颠倒二进制数中的1
和0
。与所有按位运算符一样,它首先将数字转换为32位整数,这正是你真正想要的。使用~~
可以将其还原为原始的32位整数。 - ManngoMath.floor()
,所有函数都有一个开销,其中包括存储和恢复原始状态。通常,优化编译器会寻找机会将代码原地复制以避免这种开销,但是对于像 JavaScript 这样的动态语言来说,预测更加困难。 - ManngoThe shortest version:
var myArray = ['January', 'February', 'March'];
var rand = myArray[(Math.random() * myArray.length) | 0]
console.log(rand)
| 0
的作用是将数值转换为32位整数。 - Ken Sharp| 0
本身是一种位运算,不会执行任何操作,但是浮点数在进行任何位运算之前都会被转换为整数。因此,这有点类似于 +''
不会真正执行任何操作,但可以用来将值转换为字符串。请注意,翻译时应保留原文意思,并使其更加通俗易懂。 - dshepherdMath.floor
但在这里是正确的做法。它是一个运算符,所以如果只考虑速度,它比 Math.floor
更快,因为在运行代码的任何时候,某些代码可能会执行 Math.floor = someOtherFunction
,但对于 '|' 它们无法执行相同操作。另一方面,关于 Math.floor
和 |
的区别,请尝试 Math.floor(-1.5)
和 -1.5 | 0
。顺便说一下,您不需要使用括号,因为 |
的优先级非常低。 - gman假设你想选择一个与上次不同的随机项(虽然不是真正的随机,但仍然是常见需求)...
/**
* Return a random element from an array that is
* different than `last` (as long as the array has > 1 items).
* Return null if the array is empty.
*/
function getRandomDifferent(arr, last = undefined) {
if (arr.length === 0) {
return null;
} else if (arr.length === 1) {
return arr[0];
} else {
let num = 0;
do {
num = Math.floor(Math.random() * arr.length);
} while (arr[num] === last);
return arr[num];
}
}
实现方法如下:
const arr = [1,2,3];
const r1 = getRandomDifferent(arr);
const r2 = getRandomDifferent(arr, r1); // r2 is different than r1.
如果您有固定的值(比如一个月份名称列表)并且想要一个一行解决方案
var result = ['January', 'February', 'March'][Math.floor(Math.random() * 3)]
数组的第二部分是一个访问操作,如在JavaScript中[5,6,8,7][1,2]为什么等于8中所述。
export function randChoice<T>(arr: Array<T>): T {
return arr[Math.floor(Math.random() * arr.length)]
}
function randChoice(arr) {
return arr[Math.floor(Math.random() * arr.length)]
}
var item = ['A', 'B', 'C', 'D'].find((_, i, ar) => Math.random() < 1 / (ar.length - i));
console.log(item);
如果仅用于测试目的且没有充分理由只保存在单独变量中,则可以采用这种方法。否则,其他答案(floor(random()*length
和使用单独函数)是您的选择。
const faker = require('faker');
faker.helpers.arrayElement(['January', 'February', 'March']);
正如评论者所提到的,通常不应该在生产代码中使用这个库。
Faker
中选择随机数组元素的实际方法。 - Pixxl
Math.floor(Math.random(...))
调用,它会向下取整。 - ashes999var rand = myArray[Math.random() * myArray.length>>0]
稍微快一点。 - user3546284var rand = myArray[Math.random() * myArray.length | 0]
。 - np42undefined
。在这种情况下抛出异常可能会有所帮助。 - Froxx