Home  >  Article  >  Web Front-end  >  What are the new methods of es6 number object?

What are the new methods of es6 number object?

青灯夜游
青灯夜游Original
2022-10-26 17:57:151465browse

es6 The new number methods are: 1. "Number.isFinite()", which can determine whether the specified value is a finite value; 2. "Number.isNaN()", which can detect whether the variable is a NaN; 3. "Number.parseInt()", which can convert a string into an integer; 4. "Number.parseFloat()", which can convert a string into a floating point number; 5. "Number.isInteger()", which can Determine whether the value is an integer.

What are the new methods of es6 number object?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

In ES5, there is type conversion in the global isFinite () and isNaN () methods, and there is ambiguity in the final judgment result. ES6 provides two new methods, Number.isFinite () and Number.isNaN (), on the Number object to make numerical judgments more robust. Let me take a look at these two methods next.

Number.isFinite()


In ES5, there is a global isFinite() function used to determine the parameters passed in Whether the value is a limited number. If the parameter is a string, it will be converted to a number first and then verified.

isFinite(Infinity);  // false
isFinite(NaN);       // false
isFinite(-Infinity); // false

isFinite(0);         // true
isFinite(2e64);      // true
isFinite('2e64');    // true

isFinite("0");       // true

As can be seen from the above code, the string will also be converted to a numerical value first and then judged. The isFinite() provided on the ES6 Number object is more robust and is similar to the global isFinite() function. In contrast, this method does not force a non-numeric parameter to be converted to a numeric value, which means that only numeric values ​​that are finite will return true.

Number.isFinite(Infinity);  // false
Number.isFinite(NaN);       // false
Number.isFinite(-Infinity); // false

Number.isFinite(0);         // true
Number.isFinite(2e64);      // true
Number.isFinite('2e64');	// false

Number.isFinite('0');       // false

Number.isNaN()


Unlike other values ​​in JavaScript, NaN cannot be passed through the equality operator (= = and ===), because both NaN == NaN and NaN === NaN will return false. Therefore, it is necessary to determine whether a value is NaN.

1. Generation of NaN values

NaN occurs when the result of an arithmetic operation returns an undefined or unrepresentable value. However, NaN is not necessarily used to indicate that some value is outside the representation range.

  • When you coerce some non-numeric values ​​into numeric values, you will get NaN.

  • 0 Dividing by 0 returns NaN - but dividing other numbers by 0 does not.

We know that we can use the Number() method for type conversion. Here are examples of forced type conversion to NaN:

Number(undefined)				// NaN
Number('undefined')				// NaN
Number('string')				// NaN
Number({})						// NaN
Number('10,3')					// NaN
Number('123ABC')				// NaN
Number(new Date().toString())	// NaN

As can be seen from the above examples, many The value is converted to NaN under forced type conversion. It is undoubtedly problematic to judge such a value. Let's take a look at the problem of isNaN ().

2. Problem with isNaN ()

By default, the method isNaN () exists globally and is used to determine whether it is a NaN value. What it requires is to receive Numeric type parameters, but when the parameter is not of Number type, the isNaN function will first try to convert the parameter into a numerical value, and then judge whether the converted result is NaN.

Example:

isNaN(NaN);       // true
isNaN(undefined); // true
isNaN('undefined')// true
isNaN({});        // true

isNaN(true);      // false
isNaN(null);      // false
isNaN(37);        // false

// strings
isNaN("37");      // false: 可以被转换成数值37
isNaN("37.37");   // false: 可以被转换成数值37.37
isNaN("37,5");    // true
isNaN('123ABC');  // true:  parseInt("123ABC")的结果是 123, 但是Number("123ABC")结果是 NaN
isNaN("");        // false: 空字符串被转换成0
isNaN(" ");       // false: 包含空格的字符串被转换成0

// dates
isNaN(new Date());                // false
isNaN(new Date().toString());     // true

isNaN("imooc")   // true: "blabla"不能转换成数值
                 // 转换成数值失败, 返回NaN

Combined with the results of the above example of how NaN is generated, it can be seen that using isNaN to determine whether the returned value is true is obviously not the result we want. In response to such problems, ES6 has been patched. Let’s look at the isNaN method in ES6.

3. Number.isNaN () details

ES6 provides Number.isNaN(x), through this method to detect whether the variable x is a NaN, it will be A reliable approach that does not cast the value being evaluated.

Number.isNaN(NaN);        // true
Number.isNaN(Number.NaN); // true
Number.isNaN(0 / 0)       // true

// 下面这几个如果使用全局的 isNaN() 时,会返回 true。
Number.isNaN("NaN");      // false,字符串 "NaN" 不会被隐式转换成数字 NaN。
Number.isNaN(undefined);  // false
Number.isNaN('undefined');// false
Number.isNaN({});         // false
Number.isNaN("blabla");   // false

Number.isNaN(true);   	 // false
Number.isNaN(null);   	 // false
Number.isNaN(37);   	 // false
Number.isNaN("37");   	 // false
Number.isNaN("37.37");	 // false
Number.isNaN("");   	 // false
Number.isNaN(" ");   	 // false

Through the above example, all situations of existing programs are basically covered, and there will be no problems caused by using global isNaN(). It is recommended to use Number.isNaN(x) method to determine whether it is NaN. If the Number.isNaN function is not supported, you can use the expression (x != x) to detect whether the variable x is NaN, which will be more reliable.

Number.parseInt()&Number.parseFloat()


In order to maintain the unity of the method, the global parseInt( ) and parseFloat() are ported to the ES6 Number object.

The two functions Number.isFinite () and Number.isNaN () provided on the Number object of ES6 are the same. How to prove that these two methods under Number are only transplanted globally? You can use the === operator to judge, as shown in the following example:

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

The results returned by the above code are all true, indicating that these two functions are the same as the global one and have not changed. For specific usage methods, please refer to the parseInt() and parseFloat() functions in ES5.

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

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

Port these two global methods to the Number object, in order to gradually reduce the global methods and make the language gradually modular.

Number.isInteger()


Before learning this function, let’s review how we judge a value For integers?

1、判断一个值为整数

一种方法是:任何整数都会被 1 整除,即余数是 0。利用这个规则来判断是否是整数。就有如下函数:

function isInteger(value) {
	return typeof value === 'number' && value%1 === 0;
}
isInteger(5) 		// true
isInteger(5.5) 	// false
isInteger('') 	// false
isInteger('8') 	// false
isInteger(true) // false
isInteger([]) 	// false

另一种方法是:使用 Math.round、Math.ceil、Math.floor 判断,因为整数取整后还是等于自己。利用这个特性来判断是否是整数,使用 Math.floor 示例,如下:

function isInteger(value) {
	return Math.floor(value) === value;
}
isInteger(5) 		// true
isInteger(5.5) 	// false
isInteger('') 	// false
isInteger('8') 	// false
isInteger(true) // false
isInteger([]) 	// false

上面的两种方法算是比较常用的判断方式,其他的一些方式都存在一些问题,这里就不一一列举了。但是,这两种方法都不够简洁,ES6 把判断整数提升到了语言层面,下面我们来看下 Number.isInteger() 的使用。

2、Number.isInteger () 的用法

Number.isInteger() 是 ES6 新增的函数,用来判断给定的参数是否为整数。

Number.isInteger(25) // true
Number.isInteger(25.1) // false

如果被检测的值是整数,则返回 true,否则返回 false。注意 NaN 和正负 Infinity 不是整数。

Number.isInteger(0);         // true
Number.isInteger(1);         // true
Number.isInteger(-100000);   // true

Number.isInteger(0.8);       // false
Number.isInteger(Math.PI);   // false

Number.isInteger(Infinity);  // false
Number.isInteger(-Infinity); // false
Number.isInteger("100");     // false
Number.isInteger(true);      // false
Number.isInteger(false);     // false
Number.isInteger([1]);       // false

上面的代码基本涵盖了 JavaScript 中的值的判断,在一些不支持 ES6 语法的浏览器中可以使用上面的两种方式进行 Polyfill 处理。

Number.isSafeInteger()


Number.isSafeInteger() 是 ES6 新增的函数,用来判断传入的参数值是否是一个 “安全整数”(safe integer)在数值扩展的 小节 我们介绍了最大安全整数和最小安全整数,不记得的同学可以跳过去看看。

一个安全整数是一个符合下面条件的整数:

  • 可以准确地表示为一个 IEEE-754 双精度数字;

  • 其 IEEE-754 表示不能是舍入任何其他整数以适应 IEEE-754 表示的结果。

比如,2e53 - 1 是一个安全整数,它能被精确表示,在任何 IEEE-754 舍入模式(rounding mode)下,没有其他整数舍入结果为该整数。作为对比,2e53 就不是一个安全整数,它能够使用 IEEE-754 表示,但是 2e53 + 1 不能使用 IEEE-754 直接表示,在就近舍入(round-to-nearest)和向零舍入中,会被舍入为 2e53。

安全整数范围为 -(2e53 - 1)到 2e53 - 1 之间的整数,包含 -(2e53 - 1)和 2e53 - 1。

Number.isSafeInteger(3);                    // true
Number.isSafeInteger(Math.pow(2, 53))       // false
Number.isSafeInteger(Math.pow(2, 53) - 1)   // true
Number.isSafeInteger(NaN);                  // false
Number.isSafeInteger(Infinity);             // false
Number.isSafeInteger("3");                  // false
Number.isSafeInteger(3.1);                  // false
Number.isSafeInteger(3.0);                  // true

【相关推荐:javascript视频教程编程视频

The above is the detailed content of What are the new methods of es6 number object?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What are react and es6Next article:What are react and es6