介绍几个函数
-
Math.ceil()
:向上取整
console.log(Math.ceil(1.3));
console.log(Math.ceil(-1.3));
console.log(Math.ceil(0));
-
Math.floor()
:向下取整
console.log(Math.floor(1.3));
console.log(Math.floor(-1.3));
-
Math.round()
:四舍五入
console.log(Math.round(1.4));
console.log(Math.round(1.5));
console.log(Math.round(-1.4));
console.log(Math.round(-1.5));
-
Math.random()
:[0,1) 之间的随机数(包括 0 但不包括 1),其产生的随机数位数,我见过的有 17 位到 20 位的,包括第一位的 0 和小数点
生成 [0, max] 的随机整数
parseInt(Math.random() * (max + 1),10);
Math.floor(Math.random() * (max + 1));
Math.round(Math.random() * max);
生成 [1, max] 的随机整数
parseInt(Math.random() * max,10) + 1;
Math.floor(Math.random() * max) + 1;
Math.ceil(Math.random() * max);
生成 [min, max] 的随机整数
parseInt(Math.random() * (max - min + 1) + min,10);
Math.floor(Math.random() * (max - min + 1) + min);