数组随机随机数获取

2018-08-09  本文已影响9人  Allan要做活神仙

方法:Math.floor(Math.random()*arr.length)

Math.floor() 向下取舍

例如:

document.write(Math.floor(0.60) + "<br />")
document.write(Math.floor(0.40) + "<br />")
document.write(Math.floor(5) + "<br />")
document.write(Math.floor(5.1) + "<br />")
document.write(Math.floor(-5.1) + "<br />")
document.write(Math.floor(-5.9))

输出

0
0
5
5
-6
-6

Math.random() 0-1之间随机数

document.write(Math.random())

输出

0.32551836247879984

示例用法:
获取数组中的随机元素

var arr = [1,3,4,56,7,2];
var tarEle = arr[Math.floor(Math.random()*arr.length)]; 
image.png
上一篇 下一篇

猜你喜欢

热点阅读