考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
当前回答
许多提供的解决方案将一个方法添加到一个特定的数组,这限制了它的使用仅限于该数组。这个解决方案是可重用的代码,适用于任何数组,并且可以是类型安全的。
打印稿
export function randChoice<T>(arr: Array<T>): T {
return arr[Math.floor(Math.random() * arr.length)]
}
JavaScript
export function randChoice(arr) {
return arr[Math.floor(Math.random() * arr.length)]
}
其他回答
这是一个简单的一行代码:
const randomElement = array[Math.floor(Math.random() * array.length)];
例如:
const月=(“1”,“2”,“3”、“4”,“可能”,“6”,“7”); const random = Math.floor(Math.random() * months.length); console.log(随机、几个月(随机));
Faker.js有许多生成随机测试数据的实用函数。在测试套件的上下文中,这是一个很好的选择:
const faker = require('faker');
faker.helpers.arrayElement(['January', 'February', 'March']);
正如评论者所提到的,您通常不应该在产品代码中使用这个库。
如果你想把它写在一行上,就像Pascual的解决方案一样,另一个解决方案是使用ES6的find函数来写它(基于这样一个事实,从n个项目中随机选择一个的概率是1/n):
var item = ['A', 'B', 'C', 'D']。找到((_,我,ar) = > math . random () < 1 / (ar.length - i)); console.log(项);
如果有充分的理由不将数组保存在单独的变量中,可以将该方法用于测试目的。否则,其他答案(地板(随机()*长度和使用一个单独的函数)是你的方式。
为了寻找一句真正的俏皮话,我得出了这个结论:
['January', 'February', 'March'].reduce((a, c, i, o) => { return o[Math.floor(Math.random() * Math.floor(o.length))]; })
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(“项目:”,项目);