绝对值:
console.log(Math.abs('-1')); // 隐式转换 会把字符串型 -1 转换为数字型
console.log(Math.abs('pink')); // NaN
取整:
// (1) Math.floor() 地板 向下取整 往最小了取值
console.log(Math.floor(1.1)); // 1
console.log(Math.floor(1.9)); // 1
// (2) Math.ceil() ceil 天花板 向上取整 往最大了取值
console.log(Math.ceil(1.1)); // 2
console.log(Math.ceil(1.9)); // 2
// (3) Math.round() 四舍五入 其他数字都是四舍五入,但是 .5 特殊 它往大了取
console.log(Math.round(1.1)); // 1
console.log(Math.round(1.5)); // 2
console.log(Math.round(1.9)); // 2
console.log(Math.round(-1.1)); // -1
console.log(Math.round(-1.5)); // 这个结果是 -1
我们想要得到两个数之间的随机整数 并且包含这2个整数:
Math.floor(Math.random() * (max - min + 1)) + min;
或者
Math.ceil(Math.random() * (max - min)) + min;
解释:Math.random()的范围是[0,1),为了使随机整数包含最大值,需要加一将差值范围扩大,然后向下取整;或不加一向上取整。