如何使用JavaScript从数组中选择随机值? [英] How do I choose a random value from an array with JavaScript?

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

问题描述


可能重复:

JavaScript:从数组中获取随机值





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

I have an external js with the following line:

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

我如何使它工作?

推荐答案

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;

创建网站数组,然后从数组中选择一个元素。您可以使用 Math来选择随机数。 random() ,它给出一个大于或等于0且小于1的结果。乘以数组的长度,然后取 floor (即只取整数部分,删除任何小数点),这样你就会有一个数字从0到1小于数组的长度(这将是您的数组的有效索引)。使用该结果从数组中选择一个元素。

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.

这篇关于如何使用JavaScript从数组中选择随机值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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