javascript怎么随机输出数组中的内容

javascript如何随机输出数组中的内容

javascript如何随机输出数组中的内容:

有时候我们可能需要从数组中随机抽出一项内容,下面就通过一段代码实例介绍一下如何实现此效果。

代码如下:

<script type="text/JavaScript"> 
var theArray=new Array();
theArray[0]="蚂蚁部落";
theArray[1]="蚂蚁部落一";
theArray[2]="蚂蚁部落二";
theArray[3]="蚂蚁部落三";
theArray[4]="蚂蚁部落四";
theArray[5]="蚂蚁部落五";
theArray[6]="蚂蚁部落六";
function ranFun()
{
  return parseInt(Math.random()*7);
}
document.write(theArray[ranFun()]);
</script>

以上代码可以随机输出数组中的元素,代码非常的简单,通过使用随机数函数为数组提供一个随机的索引即可。

原文地址是:http://www.51texiao.cn/javascriptjiaocheng/2015/0520/1996.html

最为原始地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=8546

1楼扬帆丶远航
7是获取数组的长度,建议直接使用theArray.length