Summary of ES6 knowledge points

Time:2021-10-25

1. Let and block level scope

for(let i =0;i<3;i++){
    let i = "foo";
    console.log(i)
}

Printout yes
Summary of ES6 knowledge points
It is equivalent to

let i = 0;
if (i < 3) {
    let i = "foo";
    console.log(i);
}
i++;
if (i < 3) {
    let i = "foo";
    console.log(i);
}
i++;
if (i < 3) {
    let i = "foo";
    console.log(i);
}
i++;

2,const
Const declared constants cannot be modified, which means that the declared constants cannot point to a new address again, not that the member data cannot be modified.
Best practice: do not use VaR, try to use const with let

3. Array
Array deconstruction

const arr = [1, 2, 3]
const [a, b, c] = arr;
console.log(a, b, c)

Print1,2,3

const arr = [1, 2, 3]
const [,,c] = arr;
console.log(c)

Print3

const arr = [1, 2, 3]
const [a,...rest] = arr;
console.log(rest)

Print[2,3]

there...The operator can only be used in the last bit

const arr = [1, 2, 3]
const [a, b, c, d = 4] = arr;
console.log(a, b, c, d)

Deconstruction greater than the array length. If the default value is not given, it will prompt undefined.

4. Object deconstruction

const obj = {name:'a',age:1};
const name ="b";
const {name:objName} = obj;
console.log(name)

When the object deconstruction and the definition constant have the same name, the deconstruction variable can be renamedobjName。 In this case, the printed name isb, the program will not report an error.

5. Template string
Tagged template string
const str = console.log`how are you`
Print out an array
Summary of ES6 knowledge points
A tag is a function.
Why is an array printed

const print = (strs)=>{
    console.log(strs)
}
const name1 = 'jim'
const name2 = 'tom'
const str = print`${name1} how are you,${name2}`

Print
Summary of ES6 knowledge points
The printed content is the content after the template label is divided. There may be embedded expressions in the template label. In fact, the array is the static content after the expression is divided, so it is an array. The template tag function can also receive the return value of the expression that may appear in the template string

const name1 = 'jim'
const name2 = 'tom'
const print = (strs,name1,name2)=>{
    console.log(strs,name1,name2)
}
const str = print`${name1} how are you,${name2}`

Print
Summary of ES6 knowledge points

6. String extension method
The beginning and end of the string, the middle of the search methodstartsWith() ,endsWith(), includes().

const str = 'he is a man.'
console.log(
    str.startsWith('he'),
    str.endsWith('.'),
    str.includes('is'),
)

Summary of ES6 knowledge points

7. Parameter default value
When a function parameter is an optional parameter value. The judgment method in the function body should judge whether it isundefined

function foo(para) {
    para = para === undefined ? true : false
}

8. Arrow function and this.
This in the arrow function always points to the current scope.

const person = {
    name:"tom",
    say: function (){
        console.log(`my name is ${this.name}`)
    },
    arrowSay:()=>{
        console.log(`my name is ${this.name}`)
    }
}

person.say();
person.arrowSay()

Print as follows
Summary of ES6 knowledge points
Another case

const person = {
    name: "tom",
    asyncSay: function () {
        setTimeout(function () {
            console.log(`my name is ${this.name}`)
        }, (1000));
    },
    asyncArrowSay: function () {
        setTimeout(() => {
            console.log(`my name is ${this.name}`)
        }, (1000));
    }
}

person.asyncSay();
person.asyncArrowSay()

Summary of ES6 knowledge points
The first line is printed asundefindeBecausesetTimeoutThe functions in the will eventually be called on the global object. Instead of getting the object in the current scope, you will get the object in the global scope.
The general solution is to add one_thisSave currentthis。 Closure mechanism

const _this = this;
console.log(`my name is ${_this.name}`)

The second line can be printed outtomBecause of the currentthisAlways point to the current scope.

9. Calculation attribute name
Can use[]Contains the name used to represent a dynamic property.

const obj = {
    [Math.random()]: 1,
    method() {
        console.log(this);
    }
}

obj.method()

Summary of ES6 knowledge points

10. Object.assign method
Object.assign()Method is used to merge objects. The first parameter is the target object, and the return value of the method is the target object.

 const source = {
    a:1,
    b:2,
 }

 const target = {
     a:3,
     c:4
 }
 const result = Object.assign(target,source);
 console.log(result)
 console.log(result === target)

Summary of ES6 knowledge points
This method is often used to copy an object

11,Object.is
Object.is()Used to determine whether two objects are equal

console.log(0 == false, 0 === false, +0 === -0, NaN === NaN, Object.is(+0, -0), Object.is(NaN, NaN))

Summary of ES6 knowledge points

12,proxy
At present, there are not many contacts.

const person = {
    name: "tom",
    age: 18,
}

const personProxy = new Proxy(person, {
  //Listen for object access
    get(target, property) {
        return property in target ? target[property] : "default"
    },
  //Set properties for proxy targets
    set(target, property, value) {
        if (property === "age") {
            if (!Number.isInteger(value)) {
                throw new TypeError(`${value} is not integer`)
            }
        }
        target[property] = value
    }
})

personProxy.age = 20
personProxy.gender = true
console.log(personProxy.name)
console.log(personProxy.any)

Summary of ES6 knowledge points

It is more powerful than defineproperty. The latter can only listen to object read and write, and the former can listen to more operations
Summary of ES6 knowledge points

In addition, it can monitor array changes.

const arr = [];
const arrProxy = new Proxy(arr, {
    set(target, property, value) {
        Console.log ("listening:", property, value);
        target[property] = value;
        return true; //  Indicates that the setting was successful
    }
})

arrProxy.push(1);
arrProxy.push(2)

Summary of ES6 knowledge points
Can judge the subscript

13. For… Of loop
for...ofCan be used in the loopbreakkeyword,forEachNo.
for...ofYou can traverse not only arrays, but also pseudo array objects
Traversal map object

const m = new Map();
m.set('a', 1);
m.set('b', 2);
for (let i of m) {
    console.log(i)
}
//Using array structure method
for (let [key, value] of m) {
    console.log(key, value)
}

Summary of ES6 knowledge points

14. Generator
GeneratorImplement a transmitter

//Lazy execution
function * createidMaker(){
 let id = 1;
 while(true){
     yield id++;
 }
}
const idMaker = createidMaker();
console.log(idMaker.next());
console.log(idMaker.next().value);
console.log(idMaker.next().value);
console.log(idMaker.next().value);
console.log(idMaker.next().value);

Summary of ES6 knowledge points

useGeneratorFunction implementationiteratormethod

const obj = {
    value: [1, 2, 3],
    english: ['a', 'b', 'c'],
    Word: ['one', 'two', 'three'],
    [Symbol.iterator]: function* () {
        const all = [...this.value, ...this.english, ...this.word]
        for (const item of all) {
            yield item
        }
    }
}

for (const item of obj) {
    console.log(item)
}

Summary of ES6 knowledge points

15,ES2016
includes()method
For array lookup,indexOfMethod cannot findNaN

const arr = ['a',1,NaN,false]
console.log(arr.indexOf('a'));
console.log(arr.indexOf(NaN));
console.log(arr.indexOf(false));
console.log(arr.includes(NaN))

Summary of ES6 knowledge points

Exponential operator

console.log(Math.pow(2, 10));
console.log(2 ** 10)

Summary of ES6 knowledge points

16,ES2017
ObjectExtension method

const obj = {
    a: 1,
    b: 2
}

//Object. Values() object value collection
console.log(Object.values(obj))
//The object. Entries () array method returns the key value pairs in the object and converts them into a map structure
console.log(Object.entries(obj))
for (let [key, value] of Object.entries(obj)) {
    console.log(key, value)
}
console.log(new Map(Object.entries(obj)))

Summary of ES6 knowledge points

 String.property.padStart,String.property.padEnd

When printing objects, they look inconsistent because of different lengths.

// String.property.padStart,String.property.padEnd
const person = {
    tom: 5,
    jerry: 16,
    williams: 120
}
for (let [name, age] of Object.entries(person)) {
    console.log(name, age)
}
console.log('String.property.padStart,String.property.padEnd')
Console.log ('fill the start and end positions of the target string with the given string ')
for (let [name, age] of Object.entries(person)) {
    //Padend has 15 fixed characters, and the blank space is filled with -
    console.log(`${name.padEnd(15,'-')} | ${age.toString().padStart(3,'0')}`)
}

Summary of ES6 knowledge points