如何从数组中获取随机元素 [英] How to get random elements from an array

查看:89
本文介绍了如何从数组中获取随机元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

JavaScript:从数组中获取随机值





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

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

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.

推荐答案

你可以随机播放数组并选择前四个。

You could shuffle the array and pick the first four.

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

现在 numbers [0] numbers [1] ...等等具有随机和唯一元素。

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

请注意,此方法可能不是洗牌阵列的最佳方式:参见是吗正确使用JavaScript Array.sort()方法进行混洗?进行讨论。

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.

这篇关于如何从数组中获取随机元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆