获取一个数组中的随机值

今天写了一个获取数组随机值的方法给同事,结果妹子同事一直不能理解为什么是Math.floor,而不用Math.round

 

方法:
Array.prototype.getRandomItem=function(){
return this[Math.floor(Math.random()*this.length)]
}

 

使用:

var arr=[1,2,3,4,5,6,'a','b','c','d'];

arr.getRandomItem();

 

为什么用Math.floor?因为数组的下标是从0开始的

其实这样想就好理解了,假设数组只有1个值,必然取arr[0],如果用Math.round,会取到1,显然不对嘛

posted @ 2016-10-28 11:11  hahaha222  阅读(3410)  评论(0编辑  收藏  举报