search
HomeWeb Front-endJS TutorialSummary of the new numerical methods in ES6 (must read)

This article brings you a summary of the new digital methods in ES6 (a must-read). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

This article introduces the new numerical methods in ES6 (ECMAScript 6).

This article will introduce you to the new methods and constants of adding Number data type. Of course, the methods employed here are not entirely new, but they can already be moved directly within and/or (e.g. isNaN()). We will practice this with some examples.

Number.isInteger()

The first method I want to introduce is Number.isInteger(). It's new to JavaScript, and you may have defined and used this method before. It determines whether the value passed to the function is an integer. If the function value is true, this method returns, if false, it exits. The implementation of this method is very simple and is native JavaScript syntax. One of the ways to rewrite this function is:

    Number.isInteger = Number.isInteger || function (number) {
      return typeof number === 'number' && number % 1 === 0;
    };

Just for fun, I rewrote this function to use a completely different method:

    Number.isInteger = Number.isInteger || function (number) {
      return typeof number === 'number' && Math.floor(number) === number;
    };

Although both of the above methods can determine Whether the passed parameters are integers, but they do not comply with the ECMAScript 6 specification. So, if you want to rewrite strictly according to ES6 specifications, please start with the following syntax:

    Number.isInteger(number)

The parameter number represents the value to be tested.

An example of using this method is shown below:

    // prints 'true'
    console.log(Number.isInteger(19));
    
    // prints 'false'
    console.log(Number.isInteger(3.5));
    
    // prints 'false'
    console.log(Number.isInteger([1, 2, 3]));

This method is supported by Node.js and all modern browsers, except Internet Explorer. If you need to support older browsers, you can use a polyfill, such as the one available on the Mozilla Developer Network for Firefox. Take a look at the code below:

    if (!Number.isInteger) {
      Number.isInteger = function isInteger (nVal) {
        return typeof nVal === 'number' &&
          isFinite(nVal) &&
          nVal > -9007199254740992 &&
          nVal <h2 id="Number-isNaN">Number.isNaN() </h2><p> If you have written JavaScript code before, this method will not be unfamiliar to you. JavaScript has a method called isNaN() exposed through the window object. This method is used to determine whether the test value is equal to NaN. It returns true, otherwise it returns false. However, there is a problem with calling window.isNaN() directly. When the test value is forced to be converted to a number, this method will return a true value. To give you a concrete idea of ​​the problem, all of the following statements will return: <strong>true</strong></p><pre class="brush:php;toolbar:false">    // prints 'true'
    console.log(window.isNaN(0/0));
    
    // prints 'true'
    console.log(window.isNaN('test'));
    
    // prints 'true'
    console.log(window.isNaN(undefined));
    
    // prints 'true'
    console.log(window.isNaN({prop: 'value'}));

What you probably want is a method that only returns true when the passed value is NaN. This is why ECMAScript 6 introduced Number.isNaN(). Its syntax is as follows:

    Number.isNaN(value)
    这value是您要测试的值。此方法的一些示例用法如下所示:
    
    // prints 'true'
    console.log(Number.isNaN(0/0));
    
    // prints 'true'
    console.log(Number.isNaN(NaN));
    
    // prints 'false'
    console.log(Number.isNaN(undefined));
    
    // prints 'false'
    console.log(Number.isNaN({prop: 'value'}));

As you can see, testing the same values ​​we get different results.

This method is supported by Node and all modern browsers, except Internet Explorer. If you want to support other browsers, a very simple polyfill for this method is as follows:

    Number.isNaN = Number.isNaN || function (value) {
      return value !== value;
    };

NaN is the only non-self value in JavaScript, meaning it is the only value that is not equal to itself.

Number.isFinite()

This method has the same background as the previous method. In JavaScript, there is such a method window.isFinite(), which is used to test whether the passed value is a finite number. Unfortunately, it also returns a true value that is coerced to a number, an example like this:

    // prints 'true'
    console.log(window.isFinite(10));
    
    // prints 'true'
    console.log(window.isFinite(Number.MAX_VALUE));
    
    // prints 'true'
    console.log(window.isFinite(null));
    
    // prints 'true'
    console.log(window.isFinite([]));

For this reason, in ECMAScript 6 there is a method called isFinite(). The syntax is as follows:

    Number.isFinite(value)

value is the value you want to test. If you test the same value from the previous snippet, you can see the results are different:

    
    // prints 'true'
    console.log(Number.isFinite(10));
    
    // prints 'true'
    console.log(Number.isFinite(Number.MAX_VALUE));
    
    // prints 'false'
    console.log(Number.isFinite(null));
    
    // prints 'false'
    console.log(Number.isFinite([]));

This method is supported by Node and all modern browsers, except Internet Explorer. You can find its polyfill on the methods page on MDN.

Number.isSafeInteger()

Number.isSafeInteger() is a brand new addition to ES6. It tests whether the passed value is a safe integer, in which case it returns true. A safe integer is defined as an integer that satisfies the following two conditions:

  • The number can be represented exactly as an IEEE-754 double

  • number The IEEE-754 representation cannot be the result of rounding any other integer to fit the IEEE-754 representation.

According to this definition, a safe integer is from -(2 to the power of 53-1)contained to 2 to the power of 53-1All integers contained.

    
    
    Number.isSafeInteger(value)
    这value是您要测试的值。此方法的一些示例用法如下所示:
    
    // prints 'true'
    console.log(Number.isSafeInteger(5));
    
    // prints 'false'
    console.log(Number.isSafeInteger('19'));
    
    // prints 'false'
    console.log(Number.isSafeInteger(Math.pow(2, 53)));
    
    // prints 'true'
    console.log(Number.isSafeInteger(Math.pow(2, 53) - 1));

Number.isSafeInteger() is supported in all modern browsers, except Internet Explorer. The polyfill for this method was taken from es6-shim by Paul Miller as:

    
    Number.isSafeInteger = Number.isSafeInteger || function (value) {
      return Number.isInteger(value) && Math.abs(value) <p> Please note that this polyfill relies on the Number.isInteger() method discussed previously, so you need to do the latter polyfill to use this method. </p><p>ECMAScript 6 also introduces two related constant values: <strong>Number.MAX_SAFE_INTEGER</strong> and <strong>Number.MIN_SAFE_INTEGER</strong>. The former represents the largest safe integer in JavaScript, which is 2 to the power of 53 - 1, while the latter represents the smallest safe integer, which is - (2 to the power of 53 - 1). </p><h2 id="Number-parseInt-and-Number-parseFloat">Number.parseInt() and Number.parseFloat() </h2><p>Number.parseInt() and Number.parseFloat() methods both belong to the same section, because unlike the ones mentioned in this article To other similar methods, they already existed in previous versions of ECMAScript. Therefore, you can use them in the same way as you currently do, and get the same results. The syntax is as follows: </p><pre class="brush:php;toolbar:false">    // Signature of Number.parseInt
    Number.parseInt(string, radix)
    
    // Signature of Number.parseFloat
    Number.parseFloat(string)

where string represents the value to be parsed and radix is ​​the radix string you want to use for conversion.

The following code snippet shows example usage:

    // Prints '-3'
    console.log(Number.parseInt('-3'));
    
    // Prints '4'
    console.log(Number.parseInt('100', 2));
    
    // Prints 'NaN'
    console.log(Number.parseInt('test'));
    
    // Prints 'NaN'
    console.log(Number.parseInt({}));
    
    // Prints '42.1'
    console.log(Number.parseFloat('42.1'));
    
    // Prints 'NaN'
    console.log(Number.parseFloat('test'));
    
    // Prints 'NaN'
    console.log(Number.parseFloat({}));

Node和所有现代浏览器都支持这些方法,Internet Explorer除外。如果您想要使用它们,您可以简单地调用它们的全局方法,如下所示:

    // Polyfill Number.parseInt
    Number.parseInt = Number.parseInt || function () {
      return window.parseInt.apply(window, arguments);
    };
    
    // Polyfill Number.parseFloat
    Number.parseFloat = Number.parseFloat || function () {
      return window.parseFloat.apply(window, arguments);
    };

相关推荐:

ES5与ES6数组方法总结

关于ES6中字符串string常用的新增方法分享

ES6里关于数字新增判断详解


The above is the detailed content of Summary of the new numerical methods in ES6 (must read). 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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)