Javascript 如何从数组中获取随机元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7158654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:06:14  来源:igfitidea点击:

How to get random elements from an array

javascript

提问by geef

Possible Duplicate:
JavaScript: Getting random value from an array

可能的重复:
JavaScript:从数组中获取随机值

var numbers = new Array('1','2','4','5','6','7','8','9','10');

I have a JavaScript Array and now want to randomly choose four different numbers from it and then express it on the page (through document.write). Obviously each time the page is reloaded by the user it would show four different random numbers.

我有一个 JavaScript 数组,现在想从中随机选择四个不同的数字,然后在页面上表达它(通过document.write)。显然,每次用户重新加载页面时,它都会显示四个不同的随机数。

回答by JJJ

You could shuffle the array and pick the first four.

您可以打乱数组并选择前四个。

numbers.sort( function() { return 0.5 - Math.random() } );

Now numbers[0], numbers[1]... and so on have random and unique elements.

现在numbers[0]numbers[1]...等等有随机和独特的元素。

Note that this method may not be an optimal way to shuffle an array: see Is it correct to use JavaScript Array.sort() method for shuffling?for discussion.

请注意,此方法可能不是洗牌数组的最佳方法:请参阅使用 JavaScript Array.sort() 方法进行洗牌是否正确?供讨论。

回答by Tim Down

If you want this to be as random as the native implementations of JavaScript's Math.random()will allow, you could use something like the following, which also has the advantages of leaving the original array untouched and only randomizing as much of the array as required:

如果您希望它像 JavaScript 的本机实现所Math.random()允许的那样随机,您可以使用如下所示的内容,它的优点还在于保持原始数组不变,并且只根据需要随机化数组:

function getRandomArrayElements(arr, count) {
    var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
    while (i-- > min) {
        index = Math.floor((i + 1) * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
    }
    return shuffled.slice(min);
}


var numbers = ['1','2','4','5','6','7','8','9','10'];
alert( getRandomArrayElements(numbers, 4) );

回答by NimChimpsky

//return a random integer between 0 and 10

document.write(Math.floor(Math.random()*11));

回答by hungryMind

var numbers = new Array('1','2','4','5','6','7','8','9','10');
document.write(numbers[Math.floor(Math.random()*numbers.length)]);