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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5708784/
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-23 18:33:03  来源:igfitidea点击:

How do I choose a random value from an array with JavaScript?

javascript

提问by don3434

Possible Duplicate:
JavaScript: Getting random value from an array

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

I have an external js with the following line:

我有一个带有以下行的外部js:

var postmessage = "hi my favorite site is http://google.com";

but is there a way to pick a site a random from an array so like this

但是有没有办法像这样从数组中随机选择一个站点

var postmessage = "hi my favorite site is +'random'";

random= http://google.com, http://yahoo.com, http://msn.com, http://apple.com

how do i make it work?

我如何使它工作?

回答by Brian Campbell

var favorites = ["http://google.com", "http://yahoo.com", "http://msn.com", "http://apple.com"];
var favorite = favorites[Math.floor(Math.random() * favorites.length)];
var postmessage = "hi my favorite site is " + favorite;

Create an array of your sites, then pick one element from the array. You do this by choosing a random number using Math.random(), which gives you a result greater than or equal to 0 and less than 1. Multiply by the length of your array, and take the floor(that is, take just the integer part, dropping off any decimal points), so you will have a number from 0 to one less than the length of your array (which will thus be a valid index into your array). Use that result to pick an element from your array.

创建一个站点数组,然后从数组中选择一个元素。您可以通过使用 选择一个随机数来做到这一点Math.random(),这会为您提供大于或等于 0 且小于 1 的结果。乘以数组的长度,并取下地板(即,只取整数部分,下降任何小数点),因此您将得到一个比数组长度少 0 到 1 的数字(因此这将是数组的有效索引)。使用该结果从数组中选择一个元素。

回答by locrizak


var sites = new Array('http://www.google.com', "http://www.stackoverflow.com")

var postmessage = "hi my favorite site is" + sites[Math.round(Math.random()*(sites.length-1))];


First stick all of your sites in an array. Then get a random number from the array length (the -1 is because an array is zero indexed and the length that is returned starts at 1)

首先将您所有的网站放在一个数组中。然后从数组长度中获取一个随机数(-1 是因为数组的索引为零并且返回的长度从 1 开始)

回答by Naveed Ahmad

Do something like this:

做这样的事情:

function getRandomSite(){
   var sites = ["google.com","bing.com","xyz.com","abc.com","example.com"];
    var i = parseInt(Math.random()*(sites.length-1));
    return sites[i];
};