ES6学习笔记8:Math对象的扩展


在ES6中,Math对象上新增了17个与数学相关的方法,这些方法只能在Math对象上调用。

Math对象的扩展

Math.trunc()

基本用法
  • Math.trunc()方法用于去除一个数的小数部分,返回整数部分。
console.log(Math.trunc(4.1)); // 4
console.log(Math.trunc(4.9)); // 4
console.log(Math.trunc(-4.1)); // -4
  • 对于非数值的类型,Math.trunc()内部会先使用Number()方法转换成数值,然后在做运算。
  • 对于空值和无法截取的整数的值,返回NaN.
在没有此方法的情况下模拟使用
Math.trunc = Math.trunc || function(x){
  return x < 0 ? Math.ceil(x) : Math.floor(x);
}

Math.sign()

  • Math.sign()方法用来判断一个数是正数?负数还是零。

对于非数值,会将其转换为数值

  • Math.sign()的返回值
  1. 参数为正数,返回+1
  2. 参数为负数,返回-1
  3. 参数为0,返回0
  4. 参数为-0,返回-0
  5. 其他值,返回NaN
在没有此方法的情况下模拟使用
Math.sign = Math.sign || function(x) {
  x = +x;
  if( x === 0 || isNaN(x)){
    return x;
  }
  return x > 0 ? 1 : -1;
}

Math.cbrt()

  • Math.cbrt()用来计算参数的立方根

  • 对于非数值,Math.cbrt()方法内部是先使用Number()方法将其转换成数值,然后做运算。

在没有此方法的情况下模拟使用
Math.cbrt = Math.cbrt || function(x) {
  var y = Math.pow(Math.abs(x), 1/3);
  return x < 0 ? -y : y;
}

Math.hypot()

  • Math.hypot()返回所有参数的平方和的平方根

假设有两个参数:xy,那么Math.hypot()等同于 x 2 + y 2 \sqrt{x^2 + y^2} x2+y2 的预算结果

  • 如果参数不是数值,Math.hypot()方法会将其转换为数值,只要有一个参数无法转换,那么就会返回NaN.

四个对数相关的方法

  1. Math.expm1()

方法Math.expm1()返回的值等同于数学公式: e x − 1 e^x-1 ex1的预算结果。

  1. Math.log1p()

方法Math.log1p()返回1+x的自然对数,等同于:Math.log(1+x),如果x小于-1,返回NaN.

  1. Math.log10()

方法Math.log10()返回以10为底的x的对数。如果x小于0,则返回NaN.

  1. Math.log2()

方法Math.log2()返回以2为底的x的对数。如果x小于0,则返回NaN.

双曲函数

  1. Math.sinh(x)返回x的双曲正弦
  2. Math.cosh(x)返回x的双曲余弦
  3. Math.tanh(x)返回x的双曲正切
  4. Math.asinh(x)返回x的反双曲正弦
  5. Math.acosh(x)返回x的反双曲余弦
  6. Math.atanh(x)返回x的反双曲x正切

Math对象已有的方法

Math.abs()

方法:Math.abs()返回参数的绝对值

console.log(Math.abs(-3)); // 3

Math.ceil()

方法:Math.ceil()是对参数的向上取整计算

console.log(Math.ceil(3.4)); // 4

Math.exp()

方法:Math.exp()ex次幂的值;e 代表自然对数的底数,其值近似为 2.71828。

console.log(Math.exp(1)); // 2.718281828459045 

Math.floor()

方法:Math.floor()是对参数的向下取整计算

console.log(Math.floor(3.4)); // 3

Math.log()

方法:Math.log()返回以自然对数(底为e)

console.log(Math.log(2.7183)); // 1.0000066849139877

Math.pow(x,y)

方法:Math.pow(x,y)返回参数x的y次幂的值

console.log(Math.pow(2,2)); // 4

注意:如果结果是虚数或者负数,则返回NaN,如果因为指数过大而引起溢出,则返回Infinity

Math.random()

方法:Math.random()返回一个0~1之间的随机数。

Math.round()

方法:Math.round()返回参数四舍五入的运算结果

console.log(Math.round(3.1)); // 3
console.log(Math.round(3.9)); // 4
console.log(Math.round(-3.9)); // -4
console.log(Math.round(-0)); // -0

Math.sqrt()

方法:Math.sqrt()返回参数平方根的运算结果

console.log(Math.sqrt(4)); // 2
console.log(Math.sqrt(-4));  // NaN
console.log(Math.sqrt(-0));  // -0 
console.log(Math.sqrt(0));  // 0 

备注:本文是自己学习阮一峰老师的《ECMAScript 6 入门》所做的笔记,大部分例子来源于此书。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值