考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
当前回答
如果你的项目中已经包含了下划线或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);
其他回答
简单功能:
var myArray = ['January', 'February', 'March'];
function random(array) {
return array[Math.floor(Math.random() * array.length)]
}
random(myArray);
OR
var myArray = ['January', 'February', 'March'];
function random() {
return myArray[Math.floor(Math.random() * myArray.length)]
}
random();
OR
var myArray = ['January', 'February', 'March'];
function random() {
return myArray[Math.floor(Math.random() * myArray.length)]
}
random();
这与@Jacob Relkin的解决方案类似,但更普遍:
这是ES2015:
const randomChoice = arr => {
const randIndex = Math.floor(Math.random() * arr.length);
return arr[randIndex];
};
该代码的工作原理是在0到数组长度之间选择一个随机数,然后返回该下标处的项。
这是一个简单的一行代码:
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(随机、几个月(随机));
如果你的项目中已经包含了下划线或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);
要获得加密强随机项形式数组使用
let rndItem = a=> a[rnd()*a.length|0]; 令RND = ()=> crypto。getRandomValues(新Uint32Array (1) [0] / 2 * * 32; var myArray = ['January', 'February', 'March']; log(rndItem(myArray))