@Wangww0925
2019-08-20T08:16:51.000000Z
字数 1988
阅读 214
ES6
前端编程工作中对数字的操作是非常多的,如果你对数字操作的不好,就很难写出令人惊奇的程序,所以这里重点学习一下ES6新增的一些数字操作方法。
二进制和八进制数字的声明并不是ES6的特性,我们只是做一个常识性的回顾,因为很多新人小伙伴会把他们当成字符串或者不知道是什么。
二进制声明:
二进制的英文单词是Binary,二进制的开始是0(零),然后第二个位置是B(注意这里大小写都可以实现),然后跟上二进制的值就可以了。
let binary = 0B010101;
console.log(binary); // 21
八进制声明:
八进制的英文单词是Octal,也是以0(零)开始的,然后第二个位置是O(欧)(注意这里大小写都可以实现),然后跟上八进制的值就可以了。
let octal = 0o666;
console.log(octal); // 438
console.log(0o777); // 511
可以使用Number.isFinite() 来进行数字验证,只要是数字,不论是浮点型还是整形都会返回true,其他时候会返回false。
console.log(Number.isFinite(11/4)); //true
console.log(Number.isFinite(11)); //true
console.log(Number.isFinite('www')); //false
console.log(Number.isFinite(NaN)); //false
console.log(Number.isFinite(undefined)); //false
console.log(Number.isFinite(null)); //false
NaN是特殊的非数字,可以使用Number.isNaN()来进行验证。下边的代码控制台返回了true。
console.log(Number.isNaN(NaN)); //true
console.log(Number.isNaN(11/4)); // false
console.log(Number.isNaN(11)); // false
console.log(Number.isNaN('www')); // false
console.log(Number.isNaN(undefined)); // false
console.log(Number.isNaN(null)); // false
console.log(Number.isInteger(123)); // true
console.log(Number.isInteger(123.1)); // false
console.log(Number.parseInt('9.18')); // 9
console.log(Number.parseFloat('9.18')); // 9.18
整数的操作是有一个取值范围的,它的取值范围就是2的53次方。我们先用程序来看一下这个数字是什么.
// 最大值
let a = Math.pow(2, 53) - 1;
console.log(a); // 9007199254740991
// 最小值
let b = -(Math.pow(2, 53) - 1);
console.log(b); // -9007199254740991
在我们计算时会经常超出这个值,所以我们要进行判断,ES6提供了一个常数,叫做最大安全整数,以后就不需要我们计算了。
consolec .log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.MIN_SAFE_INTEGER); // -9007199254740991
console.log(Number.isSafeInteger(Math.pow(2, 53)-1)); // true
console.log(Number.isSafeInteger(Math.pow(2, 53))); // false
总结: ES6数字的操作,方法很多,很零散,需要经常复习或者实战中慢慢熟悉。