当前位置:网站首页>Ecmascript6 new features

Ecmascript6 new features

2022-06-22 23:47:00 Delete your code in the middle of the night·

ECMAScript6 New characteristics

let keyword

let The keyword is used to declare variables , Use let Declared variables have several characteristics :

(1) Duplicate statements are not allowed

(2) Block level scope

(3) No variable promotion

const keyword

const The keyword is used to declare constants ,const The statement has the following characteristics

(1) The declaration must be given an initial value

(2) Duplicate statements are not allowed

(3) Value cannot be modified

(4) Block level scope

notes : Object attribute modification and array element change will not trigger const error

Application scenarios : Declare object types using const, Non object type declaration option let

Deconstruction and assignment of variables  

 ES6 Allows you to extract values from arrays and objects according to certain patterns , Assign values to variables , This is called deconstruction assignment .

            // Deconstruction and assignment of arrays 
            const arr = [' Jacky Cheung ',' Lau Andy ',' The dawn ',' Aaron Kwok '];
            let [zhang, liu, li, guo] = arr;

            // Object's deconstruction assignment 
            const lin = {
                name: ' Lin Zhiying ',
                tags: [' Driver ',' singer ',' Little whirlwind ',' actor ']
            };
            let wangfei = {
                name: ' Faye Wong ',
                age: 18,
                songs: [' Red bean ',' Fleeting years ',' ambiguous ',' legend '],
                history: [
                    {name: ' Dou Wei '},
                    {name: ' Li Yapeng '},
                    {name: ' Nicholas Tse '}
                ]
            };
            let {songs: [one, two, three], history: [first, second, third]} = wangfei;

notes : Frequent use of object methods 、 Array elements , You can use the deconstruction assignment form

Template string

  Template string (template string) It's an enhanced string , Use back quotes (`) identification

characteristic :(1) A newline character can appear in the string

           (2) have access to ${xxx} Formal output variable

             let str = `<ul>
                <li> Shen Tang </li>
                <li> Ma Li </li>
                <li> Wei Xiang </li>
                <li> Allen </li>
                </ul>`;
            let star = ' Wang Ning ';
            let result = `${star} In the last few years, he left happy fried dough twist. `;

In case of string and variable splicing, use template string

Simplify object writing

ES6 Allow in braces , Write variables and functions directly , Properties and methods as objects . This kind of writing is more concise .

             let name = ' Community security ';
             let eat = ' Bear biscuits ';
             let hobby = function(){
                console.log(' I'm a community security guard , Love bear cookies ');
             }
             // Attribute and method abbreviations 
             let intro = {
                name,
                eat,
                hobby,
                change(){
                    console.log(' To change the world ');
                }
             }

Arrow function

ES6 Allow to use   arrow  (=>) Defined function

1. General writing method

            let fn = (a, b) => {

                return a + b;

            }

Note on arrow function :

(1) Arrow function this Points to the scope under which the declaration is located this Value

(2) Arrow functions cannot be instantiated as constructors

(3) There is no arrow function arguments

(4) If there is only one parameter , Then brackets can be omitted

(5) If there is only one statement in the function body , The curly braces can be omitted , The return value of the function is the execution result of the statement

The arrow function does not change this The direction of , So it is very suitable for setting and this Unrelated callbacks , For example, array callback 、 Timer callback , Not suitable for event callbacks and object methods .

rest Parameters  

ES6 introduce rest Parameters , To get arguments to a function , Used in place of arguments

 rest Parameter is very suitable for the scenario of variable number parameter function

            // The functions and arguments similar 
            function add(...args){
                console.log(args);
            }
            add(1,2,3,4,5);

            //rest Parameter must be the last formal parameter 
            function minus(a, b, ...args){
                console.log(a,b,args);
            }
            minus(100,1,2,3,4,5,19)

 spread Extension operator

Extension operator (spread) Also three points (...). It's like rest Inverse operation of parameter , Convert an array to a comma separated sequence of parameters , Unpack the array .

           // Expand array 
           let movies = [' Smell and know women ', ' Touch and ', ' Green paper '];
           function fn(){
            console.log(arguments);
           }
           fn(...movies)

           // Expand the object 
           let first = {
            f: ' first '
           };
           let second = {
            s: ' the second '
           };
           let third = {
            t: ' Third '
           };
           let all = { ...first, ...second, ...third };

 Symbol

Basic use :ES6 A new type of raw data is introduced Symbol, Represents a unique value . It is Javascript The seventh data type of language , Is a data type similar to a string .

Symbol characteristic

(1)Symbol Value of is unique , Used to resolve naming conflicts

(2)Symbol Value cannot be calculated with other data

           // establish Symbol
           let s1 = Symbol();
           console.log(s1, typeof s1);

           // Add marked Symbol
           let s2 = Symbol(' Little flower ');
           let s2_2 = Symbol(' Little flower ');
           console.log(s2 === s2_2);

           // Use Symbol for  Definition 
           let s3 = Symbol.for(' tearful ');
           let s3_2 = Symbol.for(' tearful ');
           console.log(s3 === s3_2);

Symbol The only reasonable use of type is to store with variables symbol Value , Then use the stored values to create object properties .

Symbol Built in values

In addition to defining what you use Symbol Out of value ,ES6 It also provides 11 Built in Symbol value , Point to methods used within a language .

Symbol.hasInstance

When other objects use instanceof Operator , When judging whether it is an instance of the object , Will call this method

Symbol.isConcatSpreadable

Object's Symbol.isConcatSpreadable Property is equal to a Boolean value , Indicates that the object is used for Array.prototype.concat() when , Can I expand .

Symbol.unscopables

This object specifies the use of with When a keyword , Which attributes will be with Environmental exclusion .

Symbol.match

When executed str.match(myObject) when , If the attribute exists , It will call it. , Returns the return value of the method .

Symbol.replace

When the object is str.replace(myObject) Method call , Will return the return value of the method .

Symbol.search

When the object is str. search (myObject) Method call , Will return the return value of the method .

Symbol.split

When the object is str. split (myObject) Method call , Will return the return value of the method .

Symbol.iterator

Object to carry out for...of loop , Would call Symbol.iterator Method , Returns the default traversal of the object

Symbol.toPrimitive

When the object is converted to a value of the original type , Will call this method , Returns the original type value of the object .

Symbol. toStringTag

Call... On this object toString When the method is used , Returns the return value of the method

Symbol.species

When creating a derived object , Will use this property

iterator

iterator (Iterator) It's an interface , Provide unified access mechanism for different data structures . Any data structure only needs to be deployed Iterator Interface , You can complete the traversal operation .

(1)ES6 Creates a new traversal command  for...of loop ,Iterator Interface z Mainly for for...of consumption

(2) Original possession Iterator Interface data ( You can use for...of Traverse )

        a)Array

        b)Arguments

        c)Set

        d)Map

        e)String

        f)TypedArray

        g)NodeList

(3) working principle

1. Create a pointer object , Point to the start of the current data structure

2. The first time an object is called next Method , The pointer automatically points to the first member of the data structure

3. Next, call next Method , The pointer moves all the way back , Until it points to the last member

4. Every call next Method returns a containing value and done Object of property

When you need to customize the traversal data , Think of iterators

Set 

 ES6 Provides a new data structure Set( aggregate ). It's like an array , But the values of members are unique , The collection is implemented iterator Interface , So you can use   Extension operator   and  for...of  Traversal , Properties and methods of a collection :

(1)size   Returns the number of elements in the collection

(2)add   Add a new element , Returns the current collection

(3)delete  Remove elements , return Boolean value

(4)has   Detect whether the collection contains an element , return Boolean value

(5)clear   Empty the set , return undefined

            // Create an empty set 
            let s = new Set();
            // Create a non empty collection 
            let s1 = new Set([1,2,3,1,2,3]);

            // Collection properties and methods 
            // Returns the number of elements in the collection 
            console.log(s1.size);
            // Add a new element 
            console.log(s1.add(4));
            // Remove elements 
            console.log(s1.delete(1));
            // Check whether a value exists 
            console.log(s1.has(2));
            // Empty the set 
            console.log(s1.clear());

Map

 ES6 Provides Map data structure , It's like an object , It's also a set of key value pairs , however “ key ” Is not limited to strings , Various types of values ( Including objects ) Can be used as a key .Map It has also been realized. iterator Interface , So you can use 『 Extension operator 』 and 『for…of…』 Traversal .Map Properties and methods of :

  1. size       return Map Number of elements of
  2. set         Add a new element , Returns the current Map
  3. get         Returns the key value of the key name object
  4. has        testing Map Is there an element in , return boolean value
  5. clear      Empty the set , return undefined
// Create an empty  map
let m = new Map();
// Create a non empty  map
let m2 = new Map([
    ['name',' Silicon Valley '],
    ['slogon',' Continuously improve industry standards ']
]);

// Properties and methods 
// Get the number of mapping elements 
console.log(m2.size);
// Add mapping values 
console.log(m2.set('age', 6));
// Get mapping value 
console.log(m2.get('age'));
// Detect whether there is this mapping 
console.log(m2.has('age'));
// eliminate 
console.log(m2.clear());

 class class

 ES6 Provides a more traditional approach , Introduced Class( class ) The concept , Template as object . adopt class keyword , Classes can be defined . Basically ,ES6 Of class Can be seen as just a grammar sugar , Most of its functions ,ES5 Can do it , new class The writing method is just to make the writing method of the object prototype clearer 、 It's more like the syntax of object-oriented programming .

Knowledge point :

  1. class Declaration class
  2. constructor Define constructor initialization
  3. extends Inherited parent class
  4. super Call the parent constructor
  5. static Define static methods and properties
  6. Parent class methods can override
// Parent class 
class Phone {
    // Construction method 
    constructor(brand, color, price) {
        this.brand = brand;
        this.color = color;
        this.price = price;
    }

    // Object methods 
    call() {
        console.log(' I can call !!!')
    }
}

// Subclass 
class SmartPhone extends Phone {

    constructor(brand, color, price, screen, pixel) {
        super(brand, color, price);
        this.screen = screen;
        this.pixel = pixel;
    }

    // Subclass method 
    photo(){
        console.log(' I can take pictures !!');
    }

    playGame(){
        console.log(' I can play games !!');
    }

    // Method rewriting 
    call(){
        console.log(' I can make video calls !!');
    }

    // Static methods 
    static run(){
        console.log(' I can run programs ')
    }

    static connect(){
        console.log(' I can establish a connection ')
    }
}

// Instantiate objects 
const Nokia = new Phone(' nokia ', ' gray ', 230);
const iPhone6s = new SmartPhone(' Apple ', ' white ', 6088, '4.7inch','500w');

// Call subclass method 
iPhone6s.playGame();
// Call the override method 
iPhone6s.call();
// Call static methods 
SmartPhone.run();

Numerical expansion

1) Binary and octal

  Binary system 0b    octal 0o    Decimal system 0x

2) Number.isFinite() And Number.isNaN()

Number.isFinite() Used to check whether a value is finite

Number.isNaN() Used to check whether a value is NaN

3)Number.parseInt() And Number.parseFloat()

 ES6 Take a global approach parseInt and parseFloat, Migration to Number The above object , Use the same .

4) Math.trunc

  Used to remove the decimal part of a number , Returns the integer part .

5) Number.isInteger

 Number.isInteger() Used to determine whether a numerical value is an integer

Object extension  

ES6 Some new Object Object method

  1. Object.is Compare two values to see if they are strictly equal , And 『===』 The behavior is basically the same (+0 And NaN)
  2. Object.assign Merge of objects , All enumerable properties of the source object , Copy to target object
  3. __proto__、setPrototypeOf、 setPrototypeOf You can set the prototype of the object directly
原网站

版权声明
本文为[Delete your code in the middle of the night·]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206222124020033.html