在js代码中生成一个范围的整数,和java中的随机数生成还是有一定的区别的。
在java2中是先声明一个random对象,然后调用nextInt(int n)方法即可完成。
在js中,要用到是是Math
The above creates a random integer between 0 and 2. The number could be 0,1, or 2. Let's see more finely why this is the case.
1) Math.random() always produces a random number between 0 and 1
2) Math.random()*2 always produces a random number between 0 and 2
3) Math.round(Math.random()*2) always produces a random integer between 0 and 2
例子: