考虑:

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

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


当前回答

假设你想随机选择一件与上次不同的物品(不是真的随机,但仍然是一个常见的要求)……

/**
 * 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.

其他回答

创建一个随机值并传递给数组

请尝试以下代码..

//For Search textbox random value
var myPlaceHolderArray = ['Hotels in New York...', 'Hotels in San Francisco...', 'Hotels Near Disney World...', 'Hotels in Atlanta...'];
var rand = Math.floor(Math.random() * myPlaceHolderArray.length);
var Placeholdervalue = myPlaceHolderArray[rand];

alert(Placeholdervalue);

在我看来,与其把原型搞得乱七八糟,或者及时声明,我更喜欢把它暴露在窗口:

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)循环

假设你想随机选择一件与上次不同的物品(不是真的随机,但仍然是一个常见的要求)……

/**
 * 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.

如果你的项目中已经包含了下划线或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);

static generateMonth() { const theDate = ['January', 'February', 'March']; const randomNumber = Math.floor(Math.random()*3); 返回theDate [randomNumber]; };

在数组中设置一个常量变量,然后在数组中的三个对象中随机选择另一个常量,然后函数简单地返回结果。