“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

Record knowledge points and make progress every day. I will share my notes with you during the learning process. I hope it will be helpful for you to grow and make progress together

The Map, the Set

Reference: www.runoob.com/w3cnote/es6…

Map A Map is a structure of key and value pairs, with extremely fast search speed. For example, suppose you want to find grades based on a student’s name. If you use an Array implementation, you need two arrays:

var names = ['Michael'.'Bob'.'Tracy'];
var scores = [95.75.85];
Copy the code

Given a name, to find the corresponding score, first find the corresponding position in names and then retrieve the corresponding score from scores. The longer the Array, the longer the time. If you use a Map implementation, you only need a “name” – “score” cross reference table, directly according to the name of the score, no matter how big the table, the search speed will not be slower. In JavaScript, write a Map like this:

var m = new Map([['Michael'.95], ['Bob'.75], ['Tracy'.85]]);
m.get('Michael'); / / 95
Copy the code

Initializing a Map requires either a two-dimensional array or an empty Map. Map has the following methods:

var m = new Map(a);// 空Map
m.set('Adam'.67); // Add a new key-value
m.set('Bob'.59);
m.has('Adam'); // Whether key 'Adam' exists: true
m.get('Adam'); / / 67
m.delete('Adam'); // Delete key 'Adam'
m.get('Adam'); // undefinedSince a key can only correspond to one value, if you place a value on a key multiple times, the value behind it will flush out the value behind it:var m = new Map(a); m.set('Adam'.67);
m.set('Adam'.88);
m.get('Adam'); / / 88
Copy the code

Set A Set, like a Map, is a Set of keys but does not store values. Since keys cannot be repeated, there are no duplicate keys in a Set. To create a Set, either provide an Array as input or create an empty Set:

var s1 = new Set(a);/ / null Set
var s2 = new Set([1.2.3]); // Include 1, 2, 3
Copy the code

Repeating elements are automatically filtered in the Set:

var s = new Set([1.2.3.3.'3']);
s; // Set {1, 2, 3, "3"}
Copy the code

Note that the number 3 and the string ‘3’ are different elements. The add(key) method allows you to add elements to a Set, which can be repeated, but with no effect:

s.add(4);
s; // Set {1, 2, 3, 4}
s.add(4);
s; // Still Set {1, 2, 3, 4}
Copy the code

The delete(key) method removes an element:

var s = new Set([1.2.3]);
s; // Set {1, 2, 3}
s.delete(3);
s; // Set {1, 2}
Copy the code

What is the difference between Maps and Objects?

An Object’s key can only be a string or a Symbols, but a Map’s key can be any value.

Keys in a Map are ordered (FIFO principle), whereas keys added to an object are not.

The number of key pairs for Map can be obtained from the size property, while the number of key pairs for Object can only be calculated manually.

Each Object has its own prototype, and the key names on the prototype chain may conflict with the key names you set on the Object yourself.

For in, for of?

Example 1:

   const obj = {
        a: 1.b: 2.c: 3
    }
    for (let i in obj) {
        console.log(i) A, B, C
    }
    for (let i of obj) {
        console.log(i)// Uncaught TypeError: obj is not iterable
    }
Copy the code

Example 2:

    const arr = ['a'.'b'.'c']
    // For in loop
    for (let i in arr) {
        console.log(i)//0,1,2 returned data subscripts
    }
    // for of
    for (let i of arr) {
        console.log(i)//a,b,c
    }
Copy the code

Example 3:

    const arr = ['a'.'b']
    // Add a property to the arR array manually
    arr.name = 'qiqingfu'
    // The for in loop iterates over the name key
    for (let i in arr) {
        console.log(i) A, b, name
    }
    for (let i of arr) {
        console.log(i)//a,b
    }
Copy the code

From the above examples, it is concluded that… The in statement is used to iterate over the properties of an array or object. For in gets the key or the array of the object, the subscript of the string. For of, just like forEach, gets the value directly. For of, if you don’t get the object, you get an error.

Var let const

Var declarations can be repeated, let declarations cannot be repeated var is block-free, let is block-free var is mapped to window (it hangs a property), let is not mapped to window var can access variables above the declaration, let has a temporary dead zone, Const defines an immutable quantity, and if it is changed, it will report an error. Const is the same as let. It does not map to WindowsCopy the code

Understanding the arrow function?

1. Basic form of arrow function

let func = (num) = > num;
let func = () = > num;
let sum = (num1,num2) = > num1 + num2;
[1.2.3].map(x= > x * x);
Copy the code

2. Basic features of arrow function

(1). This refers to the parent scope of the arrow function. This cannot be changed by any method, including call, apply, or bind. The “this” of a normal function points to the object that called it.

let person = {
    name:'jike'.init:function(){
        // Add a click event to the body and see what the difference is in the this property
        document.body.onclick = () = >{
            alert(this.name);/ /?? This is the object that the browser is calling by default, mutable, right?
        }
    }
}
person.init();
Copy the code

In the example above, init is function, called with person.init, and inside this is the person itself, and the onclick callback is the arrow function, and inside this, which is the parent scope of this, which is the person, gets the name.

let person = {
    name:'jike'.init:() = >{
        // Add a click event to the body and see what the difference is in the this property
        document.body.onclick = () = >{
            alert(this.name);/ /?? This is the object that the browser is calling by default, mutable, right?
        }
    }
}
person.init();
Copy the code

In this example, init is the arrow function, and its internal this is the global window. Onclick’s this is the init function’s this, which is also the window, and the resulting this.name is undefined.

(2). The arrow function cannot be used as a constructor

// The constructor is as follows:
function Person(p){
    this.name = p.name;
}
// If the arrow function is used as the constructor, it is as follows
var Person = (p) = > {
    this.name = p.name;
}
Copy the code

Since this must be an instance of an object, and the arrow function does not have an instance, this here points elsewhere and cannot produce a Person instance, paradoxically.

(3). Arrow function has no arguments, caller, callee

The arrow function itself has no arguments. If the arrow function is inside a function, it will use arguments from the external function. To accept indefinite arguments in arrow functions, use rest arguments… To solve.

let B = (b) = >{
  console.log(arguments);
}
B(2.92.32.32);   // Uncaught ReferenceError: arguments is not defined

let C = (. c) = > {
  console.log(c);
}
C(3.82.32.11323);  // [3, 82, 32, 11323]
Copy the code

(4). The arrow function is called by call and apply. It does not change the point of this

let obj2 = {
    a: 10.b: function(n) {
        let f = (n) = > n + this.a;
        return f(n);
    },
    c: function(n) {
        let f = (n) = > n + this.a;
        let m = {
            a: 20
        };
        returnf.call(m,n); }};console.log(obj2.b(1));  / / 11
console.log(obj2.c(1)); / / 11
Copy the code

(5). Arrow functions have no prototype properties

var a = () = >{
  return 1;
}

function b(){
  return 2;
}

console.log(a.prototype);  // undefined
console.log(b.prototype);   / / {constructor: ƒ}
Copy the code

(6). Arrow functions cannot be used as Generator functions. Yield keyword cannot be used

(7). When an arrow function returns an object, add a parenthesis

var func = () = > ({ foo: 1 }); / / right
var func = () = > { foo: 1 };   / / error
Copy the code

(8). The method of the arrow function declared in ES6 class is instance method, not prototype method

//deom1
class Super{
    sayName(){
        //do some thing here}}// We can access the sayName method via super. prototype
var a = new Super()
var b = new Super()
a.sayName === b.sayName //true
// All instantiated objects share the sayName method on prototypy

//demo2
class Super{
    sayName =() = >{
        //do some thing here}}// The sayName method is not accessible via super.prototype. The method is not defined on prototype
var a = new Super()
var b = new Super()
a.sayName === b.sayName //false
// The instantiated object has its own sayName method, which requires more memory than demo1
Copy the code

Therefore, use arrow functions as few as possible in class to declare methods.

(9). Multiple arrow function is a higher-order function, equivalent to an embedded function

const add = x= > y= > y + x;
/ / equivalent to
function add(x){
  return function(y){
    return y + x;
  };
}
Copy the code

(10). Common error of arrow function

let a = {
  foo: 1.bar: () = > console.log(this.foo)
}

a.bar()  //undefined
Copy the code

This in the bar function refers to the parent scope, and the a object has no scope, so this is not a, and the print is undefined

function A() {
  this.foo = 1
}

A.prototype.bar = () = > console.log(this.foo)

let a = new A()
a.bar()  //undefined
Copy the code

The prototype uses the arrow function. This refers to its parent scope, not object A, so you don’t get the expected result

What’s the difference between an ordinary function and an arrow function?

// Arrow function
let fun = () = > {
    console.log('lalalala');
}
// Normal function
function fun() {
    console.log('lalla');
}
Copy the code

What should I notice when using arrow functions?

(3) Can't be used as a constructor. This means that you can't use the new command, otherwise an error will be thrown. (4) Can't use the yield command. Therefore the arrow function cannot be used as a Generator functionCopy the code

Understanding of the THEN () method

Then () only exists in Promise objects. 1. Then () methods are executed asynchronously. 2. When the methods preceding then() are executed, then() procedures are executed inside the THEN (). 3. Syntax: promise. Then (onCompleted,onRejected); Parameters of 4.

1. Required. (Promise) Promise object 2. Required. The execution handler function 3 that promises to run on successful completion. Optional. (onRejected) promises the error handler function to run when rejectedCopy the code

Promise principle implementation

1. The simplest implementation is based on the above application scenario, which finds that a promise can have three states, namely, pedding, Fulfilled and Rejected.

The initial state of the pedding Promise object instance is Fulfilled. This state can be interpreted as the successful state. This state can be interpreted as the failed stateCopy the code

Promise.all can wrap multiple Promise instances into a new One. Success returns an array of results, while failure returns the first reject state. The specific code is as follows:

let p1 = new Promise((resolve,reject) = >{
   resolve('It worked')})let p2 = new Promise((resolve,reject) = >{
   resolve('success')})let p3 = Promise.reject('failure')
Promise.all([p1,p2]).then((result) = >{
   console.log(result) //[' success','success']
}).catch((error) = >{
   console.log(error)
})
Promise.all([p1,p3,p2]).then((result) = >{
   console.log(result) 
}).catch((error) = >{
   console.log(error)  // Failed, type 'failed'
})
Copy the code

Promise.all is useful when handling multiple asynchronous processes, such as a page that needs to wait for two or more Ajax data to come back before loading is displayed.