这是我参与8月更文挑战的第12天,活动详情查看:8月更文挑战
JavaScript 内置对象 Math 的常用方法
abs(x)
- 用途:求绝对值。
- 语法:
Math.abs(x)
- 注意:
Math.abs()
是Math
的一个静态方法,应该通过Math.abs()
调用。(Math
不是构造器) - 参考:Math.abs()
- 示例:
Math.abs('-1'); // 1
Math.abs(-2); // 2
Math.abs(null); // 0
Math.abs("string"); // NaN
Math.abs(); // NaN
ceil(x)
- 用途:返回大于等于给定数字的最小整数。
- 语法:
Math.ceil(x)
- 参考:Math.ceil()
- 示例:
Math.ceil(-1.0) // -1
Math.ceil(-2.5) // -2
Math.ceil(3.5) // 4
floor(x)
- 用途:返回小于等于给定数字的最大整数。
- 语法:
Math.floor(x)
- 参考:Math.floor()
- 示例:
Math.floor(-1.0) // -1
Math.floor(-2.5) // -3
Math.floor(3.5) // 3
round(x)
- 用途:返回四舍五入后的整数。
- 语法:
Math.round(x)
- 只要碰到
0.5
的情况,不管是正数还是负数,都相当于向正无穷取整 - 参考:Math.round()
- 示例:
x = Math.round(20.49) // 20
x = Math.round(20.5) // 21
x = Math.round(-20.5) // -20
x = Math.round(-20.51) // -21
max([x[, y[, …]]])
- 用途:返回所有参数当中的最大值。
- 语法:
Math.max(value1[,value2, ...])
- 注意:如果没有参数,返回
-Infinity
;如果有任一参数不能被转换成数值,则返回NaN
。 - 参考:Math.max()
- 示例:
Math.max(1, 4, 2, 8, 5, 7) // 8
Math.max(...[1, 4, 2, 8, 5, 7]) // 8
min([x[, y[, …]]])
- 用途:返回所有参数当中的最小值。
- 语法:
Math.min([value1[,value2, ...]])
- 注意:如果没有参数,返回
Infinity
;如果有任一参数不能被转换为数值,则返回NaN
。 - 参考:Math.min()
- 示例:
Math.min(1, 4, 2, 8, 5, 7) // 1
Math.min(...[1, 4, 2, 8, 5, 7]) // 1
pow(x, y)
- 用途:返回基数的指数次幂。
- 语法:
Math.pow(base, exponent)
- 参考:developer.mozilla.org/zh-CN/docs/…
- 示例:
Math.pow(2, 7) // 128
random()
- 用途:生成从
0
到1
的伪随机数,不包括1
。 - 语法:
Math.random()
- 参考:Math.random()
- 示例:
// 生成 [min, max) 之间的伪随机数
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
// 生成 [min, ma) 之间的随机整数
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min; //不含最大值,含最小值
}
// 生成 [min, max] 之间的随机整数
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
}