考虑:

var myArray = ['January', 'February', 'March'];    

如何使用JavaScript从这个数组中选择一个随机值?


当前回答

编辑Array原型可能有害。这里是一个简单的函数来完成这项工作。

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
}

用法:

// Example 1
var item = getArrayRandomElement(['January', 'February', 'March']);

// Example 2
var myArray = ['January', 'February', 'March'];
var item = getArrayRandomElement(myArray);

其他回答

简单功能:

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();

Randojs使这更简单和可读:

console.log(rando(['January', 'February', 'March'])。值); < script src = " https://randojs.com/1.0.0.js " > < /脚本>

方法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);

这是一个简单的一行代码:

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(随机、几个月(随机));

这与@Jacob Relkin的解决方案类似,但更普遍:

这是ES2015:

const randomChoice = arr => {
    const randIndex = Math.floor(Math.random() * arr.length);
    return arr[randIndex];
};

该代码的工作原理是在0到数组长度之间选择一个随机数,然后返回该下标处的项。