1. What is ES6

ES6, or ECMA Script, is a standard specification for scripting languages developed by the ECMA International Organization for Standardization.

ES6 is often used as a generic term to refer to releases after ESMA Script 2015.

2. Let declares variables

New keyword for declaring variables in ES6.

1. Let declares that the variable is valid only at the block level

if (true) {
   // Let declarations have the concept of block-level scope whereas var does not
       let a = 0
       var b = 0
 }
console.log(b)/ / 0
        console.log(a)//a is not defined because the block-level scope outer bounds cannot be accessed
Copy the code

2. There is no improvement of variables in let

console.log(a) //undefined
var a = 20becausevarThe declaration will be precompiled and eventually compiled tovar a
console.log(a)
a=0So printing isundefinedAnd the followingletThere is no variable promotionconsole.log(b)/ / an error
let b = 20
Copy the code

3. Temporary dead zones

Because the let of its scope cannot be advanced and cannot be accessed from outside, a temporary dead zone is formed.

var a= 123
if(true){
    
	a=456 // Because the let in its scope cannot be advanced and cannot be accessed externally
    let a
}
Copy the code

3. Const declares constants

Function: Declares constants

Constant: A constant is the amount by which a value (memory address) cannot change

1. After a const constant is assigned, its value cannot be changed

const p =3.14
	  p=100 / / an error
Copy the code

2. When const declares a complex type, we can modify the items in it, but we cannot reassign the entire constant to change its memory address

const arr = [100.200]
	  arr[0] =400,
      arr[1] = [500]
	console.log(arr) // 400,500

	  arr=[699.799] 
	console.log(arr)/ / an error
Copy the code

Let, const, var

var let const
Functional scope Block-level scope Block-level scope
Declare a variable Declare a variable Declare constants
Variable ascension There is no variable promotion There is no variable promotion
Values can be changed Values can be changed Values are immutable (complex type memory addresses are immutable)
Allow duplicate declarations Duplicate declarations are not allowed Duplicate declarations are not allowed

4. Deconstruct assignments

ES6 allows you to extract values from arrays or objects and assign values to variables in their respective positions. This is called deconstructed assignment.

1. Array structure assignment

  const arr = ["Shen Teng"."Gu Ling"."Guan Xiaotong"."Hua Chen Yu"]
	let {user1,user2,user3,user4,user5} =arr 
    
    // The structure value is undefined if the one-to-one structure fails
    console.log(user1) / / Shen Teng
    console.log(user2)/ / Gu Ling
    console.log(user3)/ / xiaotong guan
    console.log(user4)/ / brilliance yu
    console.log(user5)//undefined
	
Copy the code

2. Object deconstruction assignment

let  person={name:"The Eight Turtles.".age:38}

// There are two ways to assign an object structureNotation 1: Direct uselet {name,age}=person
 console.log(name)/ / silly eight turtles
 console.log(age)/ / 18Method 2:let {name:youName,age=youAge} =person
 
 console.log(youName)/ / silly eight turtles
Copy the code

5. Template string

ES6 Added the method of creating a string, which is defined in backquotes.

1. The template string can be parsed with ${}

let name = ` zhang SAN `
let say=`hello,${name}How are you

Copy the code

2. You can call functions from template strings

3. Line breaks are allowed in the template string

6. Autoenforce writing of objects

1.If the attributes and values of an object are the same, you can omit themlet obj={
//name:name can be abbreviated as
	name
}

2.Methods shorthandlet obj ={
	// function(){
    
    fn(){}}Copy the code

7. Arrow function

The way functions are defined in ES6.

The way ES5 defines functionsfunction sum (num){
	console.log(num)} The way functions are defined in ES6// Omit the parentheses when there is only one argument
// When the function body is a single sentence and the code result is the return value, you can omit the braces
// If the function body has only one line, return must not be written if the result is to be returned
const sum =num= >console.log(num)
Copy the code

1. The arrow function does not bind this, which refers to this in the context of the function’s definition

2. Objects cannot be instantiated as constructors

let person =(name){
	person.name = name
}

let user = new person("The Eight Turtles.")
console.log(user) / / an error
Copy the code

3. Arguments cannot be used

let fn(){
	console.log(arguments) / / an error
}
fn(1.2.3)
Copy the code

The arrow function applies when:

The arrow function is suitable for callbacks unrelated to this, such as timers, array method callbacks, etc.

Arrow functions are not suitable for callbacks related to this, event callbacks, and object methods.

8. The initial default value of the function

ES6 allows functions to have default initial values.

  // With destruct assignment
        function request({
            name = "The Eight Turtles.",
            age = 19
        }) {
            console.log(name) // Teenage Mutant Ninja Turtles
            console.log(age) / / 18
        }

        request({
            name: Teenage Mutant Ninja Turtles
        })
Copy the code

9. The rest parameters

ES6 introduces rest arguments, which take arguments to functions instead of arguments, and output them as arrays to enhance data handling.

ES5
      function content() {
            console.log(arguments);// The result is an object
        }
        content(1.2.3.4)
        
ES6  
	  function content(a, b, ... args) {
            console.log(args)// the result is an array [3,4]
        }
        content(1.2.3.4)
        
        
Copy the code

10. Extend operators

1. Extension operators convert objects or arrays to comma-separated sequences of arguments.

Format:… The object or array to expand

let arr = [1.2.3]

console.log(... arr)/ / 1, 2, 3
console.log(arr) / / [1, 2, 3]
Copy the code

2. Extension operators can be applied to merge arrays

let arr =[1.2.3]
let arr2 = [4.5.6]
let arr3=[...arr,...arr2]
console.log(arr3) / / 6
Copy the code

3. Convert pseudo-arrays or traversable objects into real arrays

let divs = document.getElementByName('div')
divs =[...divs]
Copy the code

11. Symbol data type

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

Pay attention to

  1. The value of Symbol is unique and is used to resolve naming conflicts
  2. The Symbol value cannot be computed with other data
  3. Symbol does not define object ownership with for… In traverses the loop, but it is possible to use reflect. ownKeys to get all the key names of the object.

1. Create symbol

	let s1= symbol()

Copy the code

2. The symbol function can accept a string as an argument,

// This string represents a description of the symbol instance, which is mainly used for distinction
    let s2=Symbol("user")
 // Can be converted to a string
    String(s2) or s2. ToString// Can convert to a Boolean type! S2Copy the code

3. Symbol as attribute name

// Since each Symbol value is not equal, this means that the Symbol value can be used as an identifier for the property name of the object, which ensures that no property with the same name will appear. This is useful in cases where an object is made up of multiple modules, preventing a key from being accidentally overwritten or overwritten. -- Ruan Yifeng teacher ES6
let mySymbol = Symbol(a);// The first way
let a = {};
a[mySymbol] = 'Hello! ';

// The second way
let a = {
  [mySymbol]: 'Hello! '
};

// The third way
let a = {};
Object.defineProperty(a, mySymbol, { value: 'Hello! ' });
// Note that the dot operator cannot be used when the Symbol value is used as the object attribute name.
// All the above methods give the same result
a[mySymbol] // "Hello!"

Copy the code

4. Symbol. For () global registration method

Sometimes, we want to reuse the same Symbol value, and the symbol.for () method can do this. It takes a string as an argument and searches for a Symbol value with that argument as its name. If so, return the Symbol value, otherwise create a new Symbol with the name of the string and register it globally.

SymbolCreate a different one for each callSymbolobjectlet arr1 = Symbol("arr")
        let arr2 = Symbol("arr")
        console.log(arr1 == arr2) //false
Symbol.from global register, call now global find if there is no global createSymbolobjectlet arr3 = Symbol.for("arr")
        let arr4 = Symbol.for("arr")
        console.log(arr3 == arr4) //true
Copy the code

Symbol is most often an extension of an object

        let demo = {
            name: "I am the demo"[Symbol("hi")] () {console.log("How are you?")},Symbol("superman")] () {console.log("I'm Superman.")
            }
        }
        demo[Symbol("age")] = () = > {
            console.log("I'm 199 years old.")}console.log(demo)
Copy the code

Effect:

5. Obtain the string description of symbol

Let demo = Symbol (" hello ") console.log(demo.description) // HelloCopy the code

12. Iterators (for.. of)

Iterators are one such mechanism. It is an interface that provides a unified access mechanism for various data structures. Any data structure can be iterated by deploying the Iterator interface. Iterator interface in JS refers to its property Symbol(symbol.iterator). For example, the Symbol(symbol.iterator) property of an array is on its prototype chain.

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

Iterator: iterator: iterator: iterator: iterator: iterator

  1. Array
  2. Arguments
  3. map
  4. set
  5. String
  6. TypedArray
  7. NodeList

How iterators work:

  • Creates a pointer object that points to the start of the current data structure
  • The first time the object’s next method is called, the pointer automatically points to the first member of the data structure
  • The next method is then called repeatedly, moving the pointer back until it points to the last member
  • Each call to the next method returns an object containing the value and done attributes

Custom traversal data, write iterators manually

   let obj = {
                user: "Administrator".jurisdiction: ["Add"."Delete"."Change"."Check"].// obj is an object that has no Symbol. Iterator property, so it is created by itself

                [Symbol.iterator]() {
                    let index = 0;
                    return {
                        // Manually create the next method
                        next: () = > {
                            if (index < this.jurisdiction.length) {
                                let result = {
                                    value: this.jurisdiction[index],
                                    done: false
                                }
                                index++
                                return result
                            } else {
                                return {
                                    value: undefined.done: true // Done is true. Value is undefined
                                }
                            }
                        }
                    }
                }
            }
            // All verdicts shall be read

        for (let item of obj) { //item is self-named to represent each element in the traversal
            console.log(item);
        }
Copy the code

13. The generator

Generator functions are an asynchronous programming solution provided by ES6. (Later replaced by promise, but still used in some cases, such as interviews)

        function* gen() {
// Yield is equivalent to the pause mark of the function, or can be thought of as the separator of the function. Each time the next method is called, one piece of code is executed
                yield "The Tortoise";

                yield "Are you there?"
            }
            
            // Executes the obtained iterator object
        let centre = gen()
  // The generator function returns an iterator. The next method on the iterator yields the yield statement
        console.log(centre.next())
Copy the code

The next method can pass arguments as the return value of the yield statement

  function* hen(num) {
            console.log(num)

            let one = yield "My return value is 222";
            console.log(one);
            let two = yield "My return value is 333";
            console.log(two);
        }

        let centre = hen(111)
            // ** The next method can pass arguments as the yield statement return value **
        centre.next() // Note that the first next parameter is not recognized by the V8 engine so it is passed in hen
        centre.next(222)
        centre.next(333)
Copy the code

14.promise

Promise is a new solution to asynchronous programming introduced in ES6. Syntactically, a Promise is a constructor that encapsulates an asynchronous operation and can retrieve the result of its success or failure.

It’s so important, I wrote my own piece.

15. The Set structure

ES6 provides a new data structure called a Set. It is similar to an array, but the values of its members are unique. Collections implement the Iterator interface, so you can use “extension operators” and “for… of…” Go through.

  // Array decrement
        let arr = [1.2.3.2.2.4.5]
        let filter = [...new Set(arr)]


        / / intersection
        let arr2 = [3.3.2.4.6]
        let intersection = [...new Set(arr)].filter(item= > new Set(arr2).has(item))
        console.log(... intersection);/ / and set
        let union = [...new Set([...arr, ...arr2])]
        console.log(union);
Copy the code

Properties and methods of a Set

Properties and methods instructions
size Returns the number of collection elements
add Add a new element
delect Deletes the element and returns a Boolean value
has Checks whether the collection contains an element and returns a Boolean value
clear Empty the collection, return undefined

16. The structure of the Map

ES6 provides Map data structures. It is similar to an object, but also a collection of key-value pairs. However, the scope of “keys” is not limited to strings; all types of values (including objects) can be used as keys. Map also implements the Iterator interface, so you can use “extension operators” and “for… of…” I’m going to iterate.

Map has the same ownership and methods as Set:

Properties and methods instructions
size Returns the number of collection elements
set Add a new element that returns the current Map
get Returns the key value of the keyname object
has Returns a Boolean value that checks whether the Map contains an element
clear Empties the object and returns Boolean

        let m = new Map([["name"."The Eight Turtles."],
            ["age".19]]);console.log(m);
Copy the code

17. Class class

ES6 introduces the concept of class, which abstracts the common part of an object and refers to a broad category.

1. Create the class

/ / syntax:
	classThe name of the class{}/ / example:
	calss Super{
		
	}
Copy the code

Class constructor ()

Function: Used to pass parameters and return instance objects.

The constructor() method is the class’s constructor(default method) and is called when an instance is generated using the new command.

If we do not define the method, it will be created internally.

	class Super{
		constructor(name,age){
			this.name=name;
			this.age=age
		}
	}
	let demo = new Super("Golden Brow".19)
	console.log(demo)
Copy the code

3. Class add method

** Note: methods of the **class cannot be separated by commas, and the ES6 enhanced writing of methods does not say function.

   class Super {
            constructor(name, age) {
                    this.name = name
                    this.age = age
                }
                // Object method
            call() {
                console.log("Hello?")}goodBy() {
                console.log("Goodbye." + this.name); }}let demo = new Super("The Eight Turtles.".18)

        demo.goodBy() // Output: Goodbye
Copy the code

4. Inheritance extends of classes

   class father {
            constructor(type, vlaue) {
                this.type = type;
                this.vlaue = vlaue
            }

            show() {
                console.log('I showed it.');
                return "Show"
            }
            hide() {
                console.log("I hide.");
                return "Hidden"
            }
            load() {
                console.log("I'm loaded.");
                return "Load"}}class son extends father { // Inherits the father instance member


            hide() {
                console.log("I am a Chinese character");
            }
            text() {
                console.log(this.type);
                return this.type + 1}}let demo = new son("Text"."Value is 0")

        demo.show() // I'm showing it
        demo.hide() // I am a man (according to the prototype chain I did not have to look up)
        demo.load() // I loaded it
Copy the code

5. Super keyword

Used to access and invoke functions on an object’s parent class. You can call the constructor of the parent class as well as ordinary elements of the parent class.

Note:

Subclasses use super in constructors that must precede this. (The parent constructor must be called before using the subclass constructor.)

        class father {
            constructor(type, value) {
                this.type = type;
                this.value = value
            }

            show() {
                console.log('I showed it.');
                return "Show"}}class son extends father { // Inherits the father instance member
            constructor(type, value, name, age) {
                super(type, value) // Call the type, value attributes of the parent element
                this.name = name
                this.age = age
            }
            text() {
                console.log(this.type);
                console.log(this.value);
                console.log(this.name);
                console.log(this.age);
                super.show() //super calls the superclass method}}let demo = new son("Text"."Value is 0"."The Eight Turtles.".19)
        demo.text()
Copy the code

6. Getters and setters in class

Getters and setters are not unique to a class, but are used in Vue as well as in some cases in ES5. Some properties of an object can be method-bound.

Getter Executes the corresponding function when a property is obtained. Setters fire when set for a property.

Code:

  / * * *@description: get and set *@param {*}
         * @return {*}* /
        let userList = [
        { id: 1.name: "Xiao Ming".deposit: 200,},/ / deposit
         { id: 2.name: "Little red".deposit: 800}, {id: 1.name: "The Eight Turtles.".deposit: 1200,},]class Super {
            constructor(list) {
                    this.list = list
                }
                // Note that this is essentially a property that calls the get method
                // The get method is called to return the value of the property when it is retrieved
            get add() {
                    let sum = 0
                    for (let i = 0; i < this.list.length; i++) {
                        sum += this.list[i].deposit
                    }
                    return sum //return is the value of the add attribute
                }
                // Note that the property's set method must have arguments passed
            set add(user) {
                console.log(user); // Print the value every time the add value changes}}let demo = new Super(userList)
            // Get the add attribute value after get
        console.log(demo.add);
        // Get the value of getName after set
        demo.add = 333
        demo.add = "The Eight Turtles."
Copy the code

7. The static keyword

 * let son = new Person() * console.log(son.name); Properties that start static become static (class properties), and can only be called by the class instance to display undefined */

        class Person {
            name = "The Tortoise";
            static age = 18;

		// Static methods can only be accessed by themselves
			static sayHello(){
				console.log("Thank you for reading my notes.")}}let son = new Person()
        console.log(son.name); / / silly eight turtles
        console.log(son.age); //undefined
        console.log(Person.age); / / 18
		Person.sayHello() // Thank you for reading my notes
Copy the code

8. Readonly keywords

Readonly Indicates a read-only property that can only be read but cannot be modified. Used in typescript.

        class Person {
            // Note that this is used in typeScript
            readonly name = 'Joe'

            // Readonly can be used with static but note the order
            static readonly age = 18;
        }
        let son = new Person()
        console.log(son.name); / / zhang SAN
        console.log(Person.age); / / 18
        son.name = 'luffy' / / an error
Copy the code

9. Abstract class

// The difference between abstract classes and ordinary classes
// Abstract classes are used for inheritance, so they cannot be used to create instances
abstract  class father {
            constructor(type, value) {
                this.type = type;
                this.value = value
            }

            show() {
                console.log('I showed it.');
                return "Show"}}class son extends father { // Inherits the father instance member
            constructor(type, value, name, age) {
                super(type, value) // Call the type, value attributes of the parent element
                this.name = name
                this.age = age
            }
         }
		
		let demo = new father(1.2) // An error is reported because the abstract class cannot be instantiated
Copy the code

10. Open and close principle

The only thing the open close principle says about a class is that in multiple developers, we should not directly modify a predefined class, because other people may have introduced the class, and we may cause others to make errors. So it’s best to instantiate or inherit before changing.

18. ES6 numeric class extension

methods instructions
Number.EPSILON Represents the minimum longitude
Number.isFinite Checks if a value is finite
Number.isNaN Checks if a value is NaN
Number.parseInt String to integer
Number.isInterger Determines whether a number is an integer
Math.trunc Erase the decimal part of a number
Math.sign I’m going to say that a number is positive 1, negative 1, 0, 0

19.ES6 object extension

1. Object. Is (NaN NaN)

Comparing whether two values are strictly equal is basically the same as the “===” behavior (+0 and NaN)

2.Object.assign (Merge Object 1, merge Object 2…)

Merge rule: Merge object 1 has an attribute, merge object 2 does not add it. If both have the one after the attribute overrides the one before it.

3.Object.keys()

Iterate over all the key names of the object.

    let obj = {
            name: "Legend".age: 18.hobby: ["Basketball"."Football".Bowling ball]}// Get all the key names of the object
        console.log(Object.keys(obj));	

// Print the result:
 ["name"."age"."hobby"]

Copy the code

4.Object.values()

Iterate over all the values of the object.

     let obj = {
            name: "Legend".age: 18.hobby: ["Basketball"."Football".Bowling ball]}// Get all the values of the object
        console.log(Object.values(obj))
Copy the code

5.Object.entries()

Iterate over all the key names and values of the object.

   let obj = {
            name: "Legend".age: 18.hobby: ["Basketball"."Football".Bowling ball]}console.log(Object.entries(obj));
Copy the code

6.Object.fromEntries()

The object. fromEntries method is the inverse operation of entries and converts an array of key-value pairs into an Object

  let obj = {
            name: "Legend".age: 18.hobby: ["Basketball"."Football".Bowling ball]}let demo = Object.entries(obj)
        console.log(Object.entries(demo));
        console.log("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");
        demo = Object.fromEntries(demo)
        console.log(demo);
Copy the code

20.ES6 array extension

1. Includes () method

The Includes method checks whether an array contains an element and returns a Boolean value.

2. The flat () method

Convert a many-array to a lower-dimensional array.

   / / flat method
   // This contains a three-dimensional array
  const arr = [1[2.3], [4.5[6.7]]]

   // The flat parameter is depth
     console.log(arr.flat(2));  / /,2,3,4,5,6,7 [1]
Copy the code

3. FlatMap () method

The flatMap method is a combination of the array methods Map and Flat, because maps cannot handle multidimensional arrays.

21.ES6 String extension

1. TrimStart and trimEnd

In ES5, the.trim() method is used to remove whitespace from the left and right sides of the string

The trimStart and trimEnd methods in ES6 clear the left and right whitespace of the string, respectively.

21. The ES6 modular

It’s written in the Vue componentization section

22. Optional chain operator

// What are the optional chain operators? . A

 / / which? Check whether the property exists

 //. Returns the propertyDoes obj exist? If yes, proceedconst pen = obj ? .NPC ? .content;
Copy the code