考虑:

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;

其他回答

简单功能:

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

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

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

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

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

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

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

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

我真的很惊讶没有人尝试使用本机随机值:

array[Date.now()%array.length]

对于长度超过160000000000的数组,它将不起作用,但我相信您永远不会创建这样的数组

UPD

至于你的问题是如何从名为myArray的数组中选择随机值(与len=3),解决方案应该是:

myArray[Date.now()%myArray.length]