考虑:

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

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


当前回答

如果你需要多次获取一个随机项,那么,显然你会使用函数。一种方法是使该函数成为Array的方法。原型,但这通常会让你因为篡改内置原型而被大声斥责。

但是,你可以将方法添加到特定的数组本身:

var months = ['January', 'February', 'March'];
months.random = function() {
    return this[Math.floor(Math.random()*this.length)];
};

这样你就可以随心所欲地使用months.random(),而不会干扰通用的Array.prototype。

与任何随机函数一样,你会冒着连续得到相同值的风险。如果你不想这样做,你需要用另一个属性跟踪之前的值:

months.random=function() {
    var random;
    while((random=this[Math.floor(Math.random()*this.length)]) == this.previous);
    this.previous=random;
    return random;
};

如果你要经常做这样的事情,你不想篡改Array。原型,你可以这样做:

function randomValue() {
    return this[Math.floor(Math.random()*this.length)];
}

var data = [ … ];
var moreData = [ … ];

data.random=randomValue;
moreData.random=randomValue;

其他回答

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

$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)];

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

我找到了一种方法来解决顶部答案的复杂性,只需将变量rand连接到另一个变量,允许该数字在myArray[];的调用中显示。通过删除创建的新数组并处理它的复杂性,我提出了一个可行的解决方案:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>

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

var rand = Math.floor(Math.random() * myArray.length);

var concat = myArray[rand];

function random() {
   document.getElementById("demo").innerHTML = (concat);
}
</script>

<button onClick="random();">
Working Random Array generator
</button>

</body>
</html>

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

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.