菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
27
0

ES6 数值的扩展

原创
05/13 14:22
阅读数 48967

1. Number.isNaN()

Number.isNaN() 用来检查一个值是否为NaN

 console.log(Number.isNaN(NaN));       // true
 console.log(Number.isNaN(12))        // false
 console.log(Number.isNaN('15'))      // false
 console.log(Number.isNaN(true))      //  false
 console.log(Number.isNaN(9/NaN))      // true
 console.log(Number.isNaN('TRUE' / 0))    // true

 

2. Number.parseInt() , Number.parseFloat()

ES6 将全局方法parseInt() parseFloat(), 移植到Number 对象上面,行为完全保持不变。

// ES5 的写法
parseInt('12.34')          // 12
parseFloat('123.45#')      //  123.45


// ES6的写法
Number.parseInt('12.34')            // 12
Number.parseFloat('123.45#')       //  123.45

 

这样做的目的。是逐步减少全局性方法,使得语言逐步模块化

Number.parseInt === parseInt         // true
Number.parseFloat === parseFloat   // true

 

3. Number.isInterger()

Number.isInterger() 用来判断一个数值是否为整数

Number.isInteger(23)    // true
Number.isInteger(25.0)   // true

 

4. Math 对象的扩展

ES6 在Math对象上新增了17个与数学相关的方法。所有这些方法都是静态方法,只能在Math对象上调用。


 

 

Math.trunc() 

Math.trunc 方法用于去除一个数的小数部分,返回整数部分。

 console.log(Math.trunc(4.2));        // 4
 console.log(Math.trunc(2.9))         // 2
 console.log(Math.trunc(-4.1))        // -4
 console.log(Math.trunc(-4.9))        // -4
 console.log(Math.trunc(-0.123))      // -0

对于非数值,Math.trunc 内部使用Number方法将其先转为数值

 console.log(Math.trunc('123.456'))     // 123
 console.log(Math.trunc(true))       // 1
 console.log(Math.trunc(false))       //  0
 console.log(Math.trunc(null))        // 0

 


 

Math.sign()

Math.sign方法用来判断一个数到底是正数、负数、还是0, 对于非数值,会将其转换为数值。

它会返回五种值。

- 参数为整数,返回 +1 

- 参数为负数,返回 -1

- 参数为 0 , 返回 0

- 参数为-0 ,返回 -0

- 其他值,返回 NaN

 


 

 

Math.cbrt()

Math.cbrt() 方法用于计算一个数的立方根

 console.log(Math.cbrt(-1))      // -1
 console.log(Math.cbrt(0))       // 0
 console.log(Math.cbrt(1))       // 1
 console.log(Math.cbrt(2))       // 1.2599210498948732

 


 

 

Math.hypot()

Math.hypot  方法返回所有参数的平方和的平方根

console.log(Math.hypot(3,4))       // 5
console.log(Math.hypot(3,4,5))     //  7.0710678118654755
console.log(Math.hypot())          //  0
console.log(Math.hypot(NaN))      //  NaN
console.log(Math.hypot(3,4, 'foo'))   // NaN
console.log(Math.hypot(3,4, '5'))     //  7.0710678118654755
    

 

 

5. 指数运算符

es6 新增了一个指数运算符 (**)

2**2       // 4
2**3       // 8

 

6.Math.pow()

pow() 方法可返回x的y次幂的值

Math.pow(x,y)

 

7. BigInt 数据类型

BigInt 大整数 , 是ECMAScript的第8种数据类型

为了与Number 类型区别,BigInt 类型的数据必须添加后缀n

1234         // 普通整数
1234n      //   BigInt

// BinInt  的运算
1n + 2n   // 3n

BigInt 与普通整数是两种值,它们之间并不相等

42n ===  42

 

发表评论

0/200
27 点赞
0 评论
收藏