考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
考虑:
var myArray = ['January', 'February', 'March'];
如何使用JavaScript从这个数组中选择一个随机值?
当前回答
在我看来,与其把原型搞得乱七八糟,或者及时声明,我更喜欢把它暴露在窗口:
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)循环
其他回答
这是一个简单的一行代码:
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.sampleSize相同):
function getRandomElementsFromArray(array, numberOfRandomElementsToExtract = 1) {
const elements = [];
function getRandomElement(arr) {
if (elements.length < numberOfRandomElementsToExtract) {
const index = Math.floor(Math.random() * arr.length)
const element = arr.splice(index, 1)[0];
elements.push(element)
return getRandomElement(arr)
} else {
return elements
}
}
return getRandomElement([...array])
}
假设你想随机选择一件与上次不同的物品(不是真的随机,但仍然是一个常见的要求)……
/**
* 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.
许多提供的解决方案将一个方法添加到一个特定的数组,这限制了它的使用仅限于该数组。这个解决方案是可重用的代码,适用于任何数组,并且可以是类型安全的。
打印稿
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)]
}
方法1:
使用Math.random()函数获取(0- 1,1)之间的随机数 独家)。 将其乘以数组长度得到数字 (0-arrayLength)之间。 使用Math.floor()获取索引范围 从(0到arrayLength-1)。
Const arr = ["foo","bar"]; const randomlyypickedstring =arr[Math.floor(Math.random() * arr.length)]; console.log (randomlyPickedString);
方法2:
random(a, b)方法用于生成(a到b, b不排除)之间的数字。 取下限值,使数字范围从(1到arrayLength)。 减去1得到从(0到arrayLength-1)的下标。
const arr = [“foo”,“bar”]; const randomlyPickedString=arr[Math.floor(random(1, 5))-1]; console.log(randomlyPickedString);