功能分类: Math Applab JavaScript 少儿编程
返回一个 0 到 1 之间的随机数。
在 APP 应用里很多时候会用到取随机数的方法。使用 Math.random()
可以返回一个 0 到 1 之间的随机数。
AخA1// 返回一个 0 到 1 之间的随机数
2// 并输出到控制台日志
3console.log(Math.random()); // 类似值:0.35445672045343370
示例代码:随机移动 向前移动 4 次,每次向右转随机角度。
91// 向前移动 4 次,每次向右转随机角度
2// 取随机数,乘以 90,再做四舍五入获取随机角度
3moveForward();
4turnRight(Math.round(Math.random()*90));
5moveForward();
6turnRight(Math.round(Math.random()*90));
7moveForward();
8turnRight(Math.round(Math.random()*90));
9moveForward();
11Math.random()
Math.random() 方法不使用任何参数。
数字。返回一个 0 到 1 之间的随机数。