考虑:

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

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


当前回答

要获得加密强随机项形式数组使用

let rndItem = a=> a[rnd()*a.length|0]; 令RND = ()=> crypto。getRandomValues(新Uint32Array (1) [0] / 2 * * 32; var myArray = ['January', 'February', 'March']; log(rndItem(myArray))

其他回答

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

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

通过在数组原型上增加一个方法,可以方便地获取随机值。

在本例中,您可以从数组中获取单个或多个随机值。

您可以通过单击代码片段按钮运行以测试代码。

Array.prototype.random = function(n){ if(n&&n>1){ const a = []; for(let i = 0;i<n;i++){ a.push(this[Math.floor(Math.random()*this.length)]); } return a; } else { return this[Math.floor(Math.random()*this.length)]; } } const mySampleArray = ['a','b','c','d','e','f','g','h']; mySampleArray.random(); // return any random value etc. 'a', 'b' mySampleArray.random(3); //retun an array with random values etc: ['b','f','a'] , ['d','b','d'] alert(mySampleArray.random()); alert(mySampleArray.random(3));

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(“项目:”,项目);

~~比Math.Floor()快得多,所以当涉及到使用UI元素生成输出的性能优化时,~~赢得了比赛。更多信息

var rand = myArray[~~(Math.random() * myArray.length)];

但是,如果您知道数组将有数百万个元素,那么您可能需要在位操作符和Math.Floor()之间重新考虑,因为位操作符对大数字的表现很奇怪。请参阅下面的输出示例。

var number = Math.floor(14444323231.2); // => 14444323231
var number = 14444323231.2 | 0; // => 1559421343

下面是一个如何做到这一点的例子:

$scope.ctx.skills = data.result.skills;
    $scope.praiseTextArray = [
    "Hooray",
    "You\'re ready to move to a new skill", 
    "Yahoo! You completed a problem", 
    "You\'re doing great",  
    "You succeeded", 
    "That was a brave effort trying new problems", 
    "Your brain was working hard",
    "All your hard work is paying off",
    "Very nice job!, Let\'s see what you can do next",
    "Well done",
    "That was excellent work",
    "Awesome job",
    "You must feel good about doing such a great job",
    "Right on",
    "Great thinking",
    "Wonderful work",
    "You were right on top of that one",
    "Beautiful job",
    "Way to go",
    "Sensational effort"
  ];

  $scope.praiseTextWord = $scope.praiseTextArray[Math.floor(Math.random()*$scope.praiseTextArray.length)];