考虑:

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

其他回答

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

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

这是ES2015:

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

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

获取随机元素的通用方法:

让some_array =[‘简’,2月,3月,4月,“可能”); Let months = random_elems(some_array, 3); console.log(个月); 函数random_elems(arr, count) { 让len = arrr .length; 让查找= {}; Let TMP = []; If (count > len) Count = len; 对于(设I = 0;I < count;我+ +){ 让指数; {做 index = ~~(Math.random() * len); } while(查找中的索引); 查找[index] = null; tmp.push (arr(指数)); } 返回tmp; }

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

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

如果你需要多次获取一个随机项,那么,显然你会使用函数。一种方法是使该函数成为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;