今天寫了一個獲取數組隨機值的方法給同事,結果妹子同事一直不能理解為什么是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,顯然不對嘛
