2.1 Let keyword

  • Duplicate declarations are not allowed
  • Block-level scope
  • There is no variable promotion
  • The scope chain is not affected

Application scenario: Use let when declaring

2.2 Const keyword

  • Life must be given an initial value
  • Identifiers are generally capitalized
  • Duplicate declarations are not allowed
  • The value cannot be modified
  • Block-level scope

Note: Object property changes and array value changes do not raise const errors

Application scenario: Const is used to declare object types. Let is used for non-object types

2.3 Deconstructive assignment of variables

Es6 allows you to extract values from arrays and objects and assign values to variables according to a certain pattern, which is called deconstructed assignment

Such as:

//-- array destruct assignment --
const arr = ['one'.'two'.'three'.'four'];
let [one ,two,three,four] = arr;
/ / equivalent to
    let one = 'one';
    let two = 'two';
    let three = 'three';
    let four = 'four';
//-- object destruct assignment --
    const lin = {
        name: 'Amber Kwok'.tags: ['Tiny Times 1'.'Tiny Times 2'.'Tiny Times 3'.'actors'.'singer']}let {name, tags} = lin;
/ / equivalent to
    let name = 'Amber Kwok';
    let tags = ['Tiny Times 1'.'Tiny Times 2'.'Tiny Times 3'.'actors'.'singer'];
//-- complex structure --
    let jack = {
        name: 'jack'.age: 18.songs: ['song1'.'song2'.'song3'.'song4'].history: [{name: 'history1'},
            {name: 'history2'},
            {name: 'history3'}]};let {songs: [one,two,three],history:[first,second,third]} = wangfei;
// Equivalent to:
let one = 'song1';
let two = 'song2';
let three = 'song3';
let history = [
    {name: 'history1'},
    {name: 'history2'},
    {name: 'history3'},];let first = {name: 'history1'};
let second = {name: 'history2'};
let third = {name: 'history3'};

Copy the code

Note: Destruct assignment can be used frequently with object methods and array elements

2.4 Template String (Marked with backquotes)

Features:

  • A string can have a newline character
  • You can output variables as ${}

Such as:

let name = 'sessions';
let str = '<ul> <li> Zhou Keyu </li> <li> Mika </li> </li> </li>${name}</li>
</ul>
`
Copy the code

Note: Use template strings when concatenating strings with variables

2.5 Simplifying Object Writing

Es6 allows variables and functions to be written directly inside curly braces

Such as:


    let name = "fairy";
    let slogon = "Eternal Fairy";
    let improve = function() {
        console.log("Lovely and beautiful and generous.");
    }
    // Abbreviations for properties and methods
    let fairy = {
        name,
        slogon,
        improve,
        change() {
            console.log("Little Sister Forever."); }}console.log(fairy)
Copy the code

Note: Object abbreviations simplify the code, so abbreviate them later

2.6 Arrow Function

ES6 allows functions to be defined using [arrow] (=>)

    /** ** */
    let fn = (arg1,arg2,arg3) = > {
        return arg1 + arg2 + arg3;
    }
     /** ** */
    let fn2 = num= > {
        return num + 2;
    }
    /** ** */
    let fn3 = score= > score * 20;
    /** * 4, this refers to the value of this in the declaration scope */
    let fn4 = () = > {
        console.log(this);
    }
    let school = {
        name: 'fairy'.getName() {
            let fn5 = () = > {
                console.log(this.name); } fn5(); }}Copy the code

Note:

  • If the parameter has only one, the parentheses can be omitted
  • 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 this points to the value of this in the declared scope
  • Arrow functions cannot be instantiated as constructors
  • 5. Can’t use arguments

Note: rest parameters

ES6 introduces the rest argument, which gets arguments to functions, instead of arguments

    /** * functions like arguments */
    function add(. args) {
        console.log(args)
    }
    add(1.2.3.4.5);
    The rest parameter must be the last parameter */
    function minus(a,b, ... args) {
        console.log(a,b,args);
    }
    minus(100.101.1.2.3.4.5.6);
Copy the code

The rest argument is ideal for functions with an indefinite number of arguments

2.8 Spread extension operator

The spread operator is also three points (…) . Like the reverse of the rest argument, unpack an array by converting it into a comma-separated sequence.


    /** * spread spread array */
    let tfboys = ["fairy"."jack"."race"."lisa"]
    function fn() {
        console.log(arguments); } fn(... tfboys);/** * expands the object */
    let skillOne = {
        fairy: 'FAIRY'
    }
    let skillTwo = {
        jack: "JACK"
    }
    let skillThree = {
        race: "RACE"
    }
    let skillFour = {
        lisa: "LISA"
    }
    letgailun = {... skillOne,... skillThree,... skillTwo,... skillFour};console.log(gailun)
Copy the code

2.9 Symbol

ES6 introduces a new primitive data type Symbol, representing unique values, which is the seventh data type of the JavaScript language and is a string-like data type.

The characteristics of the Symbol

  • The value of Symbol is unique and is used to resolve naming conflicts
  • The Symbol value cannot be computed with other data
  • Object properties defined by Symbol cannot use for… In loops through, but you can use reflect.ownkeys to get all the key names of the object

Such as:

    let s1 = Symbol(a);console.log(s1, typeof s1);//Symbol() "symbol"
    // Add the symbol to the symbol
    let s2 = Symbol('fairy');
    let s2_2 = Symbol('fairy');
    console.log(s2 == s2_2)//false
    // Use the Symbol for definition
    let s3 = Symbol.for('fairy');
    let s3_2 = Symbol.for('fairy');
    console.log(s3 == s3_2);//true
Copy the code

Note: Think of Symbol for unique scenarios

2.10 the iterator

An Iterator is an interface that provides a unified access mechanism for a variety of data structures. Any data structure can be iterated by deploying the Iterator interface.

1. ES6 created a new traversal command for… The of loop is an Iterator interface for… Of consumption

Iterator: iterator: iterator: iterator

  • Array
  • arguments
  • set
  • map
  • string
  • typedArray
  • NodeList

Note: When you need to customize traversing data, think of iterators

2.11 Generators such as:

function * gen() {
        yieId : 'Never had ears';

        yieId : 'Never had a tail';
    
        return 'That's strange';
    }
    let iterator = gen();
    console.log(iterator.next());
    console.log(iterator.next());
    console.log(iterator.next());
Copy the code

2.12 Promise

Promise is a new solution to asynchronous programming introduced in ES6. Promise is a constructor that encapsulates an asynchronous operation and can get a failure or success note.

Promise constructor: promise(excutor){} promise.prototype.then promise.prototype.catch methodCopy the code

2.13 the Set

Data structures (sets), similar to arrays, in which the values of the members are unique. Sets implement the Iterator interface, using the [extension operator] and [for…of…] For traversal, properties and methods of the collection:

  • Size returns the number of elements in the collection
  • Add adds a new element and returns the current collection
  • Delete Returns Boolean for deleting an element
  • Has checks whether the collection contains an element, returning Boolean
  • Clear Clears collection returns Undefined

Such as:

    // Create an empty collection
    let s = new Set(a);// Create a non-empty collection
    let s1 = new Set([1.2.3.1.2.3])
    // Returns the number of elements in the collection
    console.log(s1.size);/ / 3
    // Add a new element
    console.log(s1.add(4));/ / the set {1, 2, 3, 4}
    // Delete elements
    console.log(s1.delete(1));//true
    // Check if a value exists
    console.log(s1.has(2));//true
    // Clear the collection
    console.log(s1.clear());//undefined
Copy the code

2.14 the Map

Es6 provides map data structures that are similar to objects, collections of key-value pairs, but the range of “keys” is not limited to strings. Values of all types (including objects) can be used as “keys”, as can [extension operators] and [for…of…]. I’m going to iterate. Map properties and methods

  • Size Returns the number of map elements
  • Set adds a new element that returns the current map
  • Get returns the key value of the keyname object
  • Has checks whether the map contains an element, returning Boolean
  • Chear clears collection to return Undefined

Such as:

    // Create an empty map
    let m = new Map(a);// Create a non-empty map
    let m2 = new Map([['name'.'fairy'],
        ['flogon'.'Super Super cutest thing in the universe']]);// Get the number of mapping elements
    console.log(m2.size);/ / 2
    // Add the mapping value
    console.log(m2.set('age'.6))/ / the map (3) {" name "= >" fairy ", "flogon" = > "super invincible universe most lovely", "age" = > 6}
    // Get the mapping value
    console.log(m2.get('age'))/ / 6
    // Check if the mapping exists
    console.log(m2.has('age'))// true
    / / remove
    console.log(m2.clear())//undefined
Copy the code

2.15 class class

Es6 provides a more traditional language approach, introducing the concept of class

Such as:

/ / parent class
    class Phone {
        // constructor
        constructor(brand, color, price) {
            this.brand =  brand;
            this.color = color;
            this.price = price;
        }
        // Object method
        call() {
            console.log('I can make a phone call')}}/ / subclass
    class SmartPhone extends Phone {
        constructor(brand, color, price, screen, pixel) {
            super(brand, color, price);
            this.screen = screen;
            this.pixel = pixel;
        }
        // Subclass methods
        photo() {
            console.log("I can take pictures.");
        }
        playGame() {
            console.log("I can play games.")}// Method override
        call() {
            console.log("Method override")}// Static method
        static run() {
            console.log("I can operate normally.")}static connect() {
            console.log("I can make a connection.")}}// instantiate the object
    const Nokia = new Phone('Lokia'.'grey'.230);
    const iPhone6s = new SmartPhone('apple'.'white'.6088.'4.7 inch.'500w');
    // Call the subclass method
    iPhone6s.playGame();// I can play games
    // Call the override method
    iPhone6s.call();// Method override
    // Call static methods
    SmartPhone.run();// I can run normally
Copy the code