1 Overview of ECMAScript and JavaScript

Browser side JavaScript: ECMAScript/BOM/DOM node JavaScript: ECMAScript/nodeAPI ECMA: European Computer Standards Association ECMAScript: A set of syntax standards. ECMAScript is a specification for JavaScript. JavaScript is an implementation of ECMAScript.Copy the code

1.1 Major releases of ECMAScript

ECMAScript3.0 for short ES3 ES5.0 / ES5.1 added some new extensions ES6 In June 2015, also called ES2015 (after a new version in June every year) ES7 ES2016 ES8 ES2017 ES9 ES2018 ES10 ES2019 ES11 ES2020Copy the code

ECMA reference document ES6.ruanyifeng.com/

2 keyword extension

2.1 Let keyword

Use to declare variables, similar to varCopy the code
Let variables can have block-level scope. Let global variables are no longer properties of top-level objectsCopy the code

2.2 Let and block-level scope

// Bind the three buttons to a click event and click output index number
let btn = document.querySelectorAll('button')

for (var i = 0; i < btn.length; i++) {
    btn[i].onclick = function () {
      console.log(i); / / 3 3 3
    };
  }

for (let i = 0; i < btn.length; i++) {
    btn[i].onclick = function () {
      console.log(i); / / 0 1 2
    };
  }
Copy the code

2.3 Const keyword

A constant that cannot be changed. Purpose: A program's configuration information is traditionally defined as a constantCopy the code
Features: (1) Values cannot be modified, let alone repeated declarations; (2) variables cannot be promoted; (3) Global, local, and block-level scopes; (4) Global constants are not attributes of windowCopy the code

Shorthand for object

const name = 'Ming'
const age = '18'

// Attributes with the same name can be abbreviated
const obj = {
  name
  age
  say() {   // Method shorthand}},console.log(obj) // {name: 'xiao Ming ', age: '18'}
Copy the code

4 Deconstruct the assignment

4.1 Array destruct assignment

// 1
const [a, b, c] = [value1, value2, value3]

// 2. Modify the value of the variable
[a, b, c] = [value1, value2, value3]

// 3 Complex array (ensure that both sides of the array form the same)
const [a, [b], [c, [d,e]]] = [100[200], [300[400.500]]]

// 4. You can declare variables with default values (similar to function parameters)
const [a, b, c, d = 5] = arr 
console.log(d) / / 5
Copy the code

4.2 Object destruct assignment

// Short form
{name, age} = {name: 'Joe'.age: 18} // Zhang SAN, 18

// Object form
const obj = {
  name: 'Ming'.age: 18.sex: 'male'.love: {
    eat: 'eat'.sleep: 'sleep'.peas: 'Play Beans',}}const { name, age, sex } = obj
console.log(name, age, sex) // Xiao Ming is 18 male

// Deconstruct duplicate names
const { name: myname } = obj
console.log(myname) / / xiao Ming

// Nested deconstruction
const { love: { sleep } } = obj
console.log(sleep) / / sleep
Copy the code

5 String Extension

5.1 Template Character String

Two back quotes` `${variable} directly parses ${expression} to get the result of the expressionCopy the code

5.2 New methods for string objects

1) ES5

Trim () removes the space on both sidesCopy the code

(2) the ES6 +

EndsWith () returns a Boolean value. Includes () returns a Boolean value. Repeat () padStart() ES8 completion//message.padStart(100, '#')PadEnd () ES8 completion//message.padEnd(100, '#')
matchAll()   ES10  message.matchAll(/\w/) // Return iterator (which is the result of all matches)
trimStart()  ES10
trimEnd()    ES10
Copy the code

The extension of 6 values

6.1 Exponential operator (**) ES7

2支那4;  // Calculate 2 to the fourth power
2支那2支那3;// Count the right hand side first
Copy the code

6.2 Binary and octal representation

/ / binary
0b101010

/ / octal
0o17

// The syntax is more reasonable than the previous octal representation, and is available in strict mode (starting with 0 indicates octal, strict mode is not available).
Copy the code

6.3 New methods for the Math object

Math.trunc() removes the decimal partMath.sign() determines whether a number is positive, negative, or0
MathTake the cube root of.cbrt()MathFind the square root of the sum of the squares of all parameters (used to calculate the hypotenuse length by Pythagorean theorem)Copy the code

7 function extension

7.1 Default Parameter Values

// ES6
function fn(A, b = default values) {}// ES6
function fn(a,b) {
    if (b === undefined) {b = default}}Copy the code

7.2 rest parameters

// 1, arguments get arguments
// function fn() {
// console.log(arguments);
// }

// 2. Obtain rest parameters
function fn(. numbers) {
    console.log(numbers); // Get an array containing all the arguments; The name of numbers is as long as it complies with the naming convention of the identifier name} andargumentsLike the REST parameter is an array,argumentsYou get a pseudo-arrayCopy the code

7.3 Arrow Function

(1) grammar

// The previous way to define a function (expression)
const fn = function () {}

// Arrow function
const fn = () = > {}

// This is shorthand for the arrow function. If there is only one argument, the parentheses can be omitted
const fn = name= > {}

// There is only one argument and only one return statement
const fn = num= > num * num

// If an object is returned
const fn = name= > ({ name: name })
Copy the code

(2) the characteristics of

1. thisPointing to. It doesn't matter who called the arrow function, it depends on where the arrow function is declared, whether it's nested inside the function, and if it's nested inside the function, look at the outer functionthisPoint; If not nested by a function, point towindow
   
2.Cannot get Aruguments inside the arrow function. Use the REST argument instead3.Arrow functions cannot be used as constructors4.Arrow functions cannot be used as generatorsCopy the code

③ Application Scenario

Usage scenario: Not suitable as a callback: Add method (this points to) constructor generator functions to an objectCopy the code

7.4 New properties of function objects

Name Returns the name of the function (given when declaring the function)Copy the code

8 Array Extension

8.1 Extension operators

(1) definition

The inversion of rest parameters turns the array into a comma-separated sequence of parametersCopy the code

(2) application

const nums = [100.200.300.250];
console.log(... nums);// 100 200 300 250

// 1. Call array pass parameterfn.call({}, ... nums); fn.apply({}, nums);// 2. Calculate the largest element in the array
console.log(Math.max(... nums));// 3. Append the members of one array to the end of another array
const names = ["Cao cao.'aiaa'.'liu bei']; nums.push(... names);Nums, push(' Cao Cao ', 'Zhang Ren ',' Liu Bei ')
console.log(nums);   //[100, 200, 300, 250, "Cao Cao "," Zhang Ren ", "Liu Bei "]

// 4. Clone the array
// const nums1 = nums; // Reference type
const nums1 = [...nums];  / / clone
nums1[2] ='La la la la';
console.log(nums1); //[100, 200, "la la la ", 250," Cao Cao ", "Zhang Ren "," Liu Bei "]
console.log(nums);  //[100, 200, 300, 250, "Cao Cao "," Zhang Ren ", "Liu Bei "]

// 5. Merge arrays
const newArr = [...nums, ...nums1, ...names];
console.log(newArr);

// 6. Convert strings and array-like objects into arrays
// Convert a string to an array
const newArr1 = [...'hello'];
console.log(newArr1); // ["h", "e", "l", "l", "o"]

// 7. Convert array-like objects to arrays
const btns = document.querySelectorAll('button');
console.log(btns); 
console.log([...btns]); 
Copy the code

(3) Deconstruct the REST parameters of the assignment version

// Use with destruct assignment (destruct assignment version of rest parameters)
const [a, ...b] = [10.20.30.40.50.50.60];
console.log(a, b);  // a is 10, b is an array [20, 30, 40, 50, 50, 60]
Copy the code

8.2 Added methods to the Array function

Array.from() converts the class array/string to a pure arrayArray.of() creates an array with any number of parameters.Copy the code

8.3 Methods to add an Array Instance

The find() argument is a callback function that returns the index of the first element that satisfies the condition. The findIndex() argument is a callback function that returns the index of the first element that satisfies the condition. Fill () fills the array, overwriting all the elements in the array; The Array includes() created by padding new Array (20) determines whether the Array contains an element and returns a Boolean value; FlatMap () is a callback function, which is equivalent to the combination of map and flat. ES7 adds flat(), which defaults to 1 and can be set to Infinity, regardless of dimensionCopy the code

9 Object extensions

9.1 Attribute name expression

{[expression]: value, property name: value}Copy the code

9.2 Super keyword

1. superA prototype that points to the instance that called the function2.Only in methods of objectssuperKeyword, and the shorthand form defines the method {foo(){
        super; / / get super}}Copy the code

9.3 Extension Operators for Objects… (new) ES9

Definition: convert an object into a comma-separated sequence of key-value pairs: destruct assignment of an object, object operation (object merge, object clone)Copy the code
// Define the object
 const obj = {
    name: "Cao cao.age: 100.say() {
      console.log('My Name is ' + this.name); }};console.log({ ... obj });/ / equivalent to
console.log(name:"Cao cao.age:100.say:fn);

// Object clone (shallow clone)
constobj2 = { ... obj }; obj2.name ='liu bei';
console.log(obj2);// {name: "liu Bei ", age: 100, say: ƒ}
console.log(obj); // {name: "Cao Cao ", age: 100, say: ƒ}

// If an object merge has a property of the same name, the latter overwrites the previous one
const obj3 = { width: 100.height: 200.name: 'sun' };
constobj4 = { ... obj, ... obj3 };console.log(obj4); // {name: "sun quan ", age: 100, width: 100, height: 200, say: ƒ}

// For deconstructive assignment of objects
const{ age, ... b } = obj;console.log(age); / / 100
console.log(b);   // {name: "Cao Cao ", say: ƒ}
Copy the code

9.4 Added methods to the Object function

Object.is() compares two pieces of data for equality and returns a Boolean value. Similar to equality, differentNaNIs equal to Nan, plus0And -0Not equal to theObject.assign() merges objectsObjectGetOwnPropertyDescriptor () to obtain a certain attribute description information of its ownObjectGetOwnProppertyDescriptors () for the description of the objects all its attributes information ES8 addedObject.getPrototypeof () Gets the prototype of the objectObject.setprototypeof () sets the prototype for the objectObject.keys() returns an array consisting of the object's property names.Object.values() returns an array of the property values of the object. ES8 newObject.entries() returns a two-dimensional array of property names and property values added by ES8Object.geTownPropertyNames () returns an array of the object's property namesObject.formEntries()   ObjectThe inversion of.entries () is added in ES8Copy the code

Class 10 grammar

10.1 Defining a Class (Constructor)

  / / define the class
  class Person {
    // properties are added to the instance
    // Declare all properties here
    name = null;
    age = null;

    // Define the constructor to be executed automatically when instantiated
    constructor(name, age = 10) {
      this.name = name;
      this.age = age;
    }

    // method to add to the prototype
    say() {
      console.log('MY Name is ' + this.name);
    }
    eat() {
      console.log('My age is ' + this.age);
    }

    // Static methods are not added to the instance, the constructor's own methods
    // static getClassName() {
    // console.log(' class name is the method of the Person constructor itself ');
    // }
  }
  // Person.getClassName(); // Equivalent to person.getClassName = function(){}

  console.log(Person); // Output the entire function
  console.log(typeof Person); // Function
  console.log(Person.name); // Person ===> name refers to the name of the object

  // Cannot be called
  // Person();

  / / instantiate
  var p = new Person("Cao cao.19);
  console.log(p); // Person {name: "cao Cao ", age: 19}
  p.say(); // MY Name is Cao Cao

  var p1 = new Person('lyu3 bu4'.21);
  console.log(p1); // Person {name: "吕布", age: 21}
  p1.say(); // MY Name is Lu Bu

  var p2 = new Person();
  console.log(p2); // Person {name: undefined, age: 10}
Copy the code

Note:

A class defined by class is essentially a function, but cannot be called, only instantiated

Typeof class name === ‘funciton’

10.2 instantiation

newThe name of the class.newClass name (constructor parameter);Copy the code

Note:

① Attributes defined in the class are added to the instance

② Methods defined in the class are added to the stereotype

10.3 Static Methods

class Person{
    staticMethod name () {}} Person. Method name ()// Static methods are not added to instances, but to the constructor (class) itself
Copy the code

10.4 getter and setter

class Person {
    firstName = 'Oriental';
    lastName = 'not';

    get fullName() {
      return this.firstName + '_' + this.lastName;
    }

    set fullName(val) {
      const name = val.split('_');
      this.firstName = name[0];
      this.lastName = name[1]; }}let p = new Person();
  console.log(p); //Person {firstName: "", lastName:" "}

  console.log(p.fullName); // Can read and write Oriental _ _
Copy the code

10.5 inheritance

1. Use extends to inherit to the 2: after a subclass an instance of the prototype of pointing to an instance of the parent subclass own prototype points to the parent class (static method can also be inheritance). 3. You can add properties and methods on a subclass. 4. Override a method on a subclass, which must call super().Copy the code
classA subclassextendsThe parent class{
    constructor() {
        super();
    }
}
Copy the code

11 New Data Types (original types)

11.1 Symbol

1.To create aSymbolData (only call, not instantiate)Symbol(a)2.(1) Each symbol type is unique. ② Data of type symbol can be used as attribute names, just like strings3.Application: Add properties to an object (not overwritten)4.Note :(can be used as an object property name, (string) symbol is created uniquely)for. In,ObjectThe keys (),ObjectThe values (),ObjectEntries (),Object.geTownPropertyNames () When none of these methods can get the property nameSymbolProperties of typeObject.geTownPropertySymbols () gets the name of the property whose type is symbolReflect.ownKeys(obj) retrieve all properties of the object itself (regardless of the type of the property name)Copy the code

11.2 BigInt (ES10)

(1) security number

throughNumberMAX_SAFE_INTEGER andNumber.min_safe_INTEGER Two attribute gains If an integer exceeds this range and cannot be stored as an integer, the calculation will be inaccurateCopy the code

(2) BigInt type

// 1
var a = 100n
console.log(typeof a); //bigint

// 2
var b = BigInt(1000)
console.log(b); //1000n
Copy the code
BigInt data is suitable for large number operations. Data of bigInt type can only be summedBigIntData of type number cannot be interoperated with data of type numberCopy the code

12 Set and Map

12.1 the Set

1) describe

An unordered and unrepeated set of valuesCopy the code

Create data of type Set

new Set(a);// Create an empty Set
new Set(array);// Change the array to a Set, removing duplicate values
new Set(Array of classes)Copy the code

③ Set instance methods

Add (value) Adds a value delete(value) deletes a value has(value) Determines if a value exists clear() deletes all values keys() returns the iterator values() returns the iterator entries() returns the iterator ForEach () is used to iterate over the size attribute to get the number of Set membersCopy the code

(4) Set application

1.Implement array deduplicatingconst arr = new Set([100.200.300.400.300.500.500.500]);
console.log(arr); //Set(5) {100, 200, 300, 400, 500}
Copy the code

12.2 the Map

1) describe

ObjectAn object is a collection of key-value pairs. The property name is a key and the property value is a value.MapLike an object, it is a collection of key-value pairs. The Key of an object can only be a string sumSymbolType,MapThe Key of can be of any typeCopy the code

(2) to create a Map

// Create null
new Map(a);// When creating, specify the initial value
new Map([
    [key,value],
    [key,value]
]);
Copy the code

③ Map instance methods

Get (key) Get the value of the specified key set(key,value) set or add the value of the specified key delete(key) Delete the specified key and other values clear() Clear all has(key) Determine whether a key exists keys() Return the traverser, The set values() of all keys returns a traverser, the set entries() of all values returns a traverser, and the set (two-dimensional) of all key-values forEach() is used for traversalCopy the code

13.2 iterable Traversable objects

What is an iterable object

The data structure where the iterator interface is deployed is called'iterable'(traversable object) can be usedfor. Iterator interfaces are deployed in data structuresSymbol. Iterator property on an object that only hasSymbol. Iterator property that points to a function that returns a iterator. The object isCopy the code

(2) a data structure that implements the iterator interface (iterable objects)

Array
Set
Map
String
Arguments
NodeList
HTMLcollection
Copy the code

14 Generator Generator

14.1 What is a generator

A generator is a function that generates a traverserCopy the code

14.2 Defining generators

function* Generator name () {
     yieldValue;yieldValue;yieldValue;yieldValue; }Copy the code

14.3 Yield keyword

The YEILD key returns a value, which is given every time it iteratesyieldCalls next() to theyieldIt will stop; The next call to next() moves on to the nextyieldstopCopy the code

When a generator function is called, it is not executed inside the function

The code inside the generator function is executed only when next() is called; The execution stops at yield

14.4 Deploy the Iterator interface to an object using the generator function

const obj = {
    name: "Cao cao.age: 18.score: 80.height: 170
};

// Change obj to an iterable
// Deploy the Iterator interface
obj[Symbol.iterator] = function* (){
    for (let i in obj) {
        yield[i, obj[i]]; }};for (let i of obj) {
    console.log(i); // Iterable objects
}
Copy the code

15 modules

15.1 Exporting Data from a Module

// Inside the module
function say() {}
function eat() {}

export {
    say,
    eat
}
Copy the code

15.2 Importing a Module

import {say, eat} from 'Module file path';
Copy the code

16 summary

16.1 Data types in ECMAScript

Primitive type (value type) : string, number, Boolean,null,undefined, symbol, Bigint Object types: Array, Object, Regexp, set, map......Copy the code

16.2 Ways to declare variables in ECMAScript

1,var
2,function3,let4,const (constant) 5,class6,import
Copy the code

16.3 Array flattening

const arr = [['a'.'b'], [10[100.200]], [['A'.'B'], ['一'.'二']],1000,];

  / / way
  //console.log(arr.flat(Infinity)); / / / "a", "b", 10, 100, 200, "a", "b", "a", "2", 1000]

  // Method 2 uses the disadvantages of the string join method: all elements of the array will be of string type
  //const arr2 = arr.join().split(',');
  //console.log(arr2); / / / "a", "b", "10", "100", "200", "a", "b", "a", "2", "1000"]

  // Method 3: recursion
  console.log(flatArray(arr));

  function flatArray(array) {
    // Create an empty array
    let res = [];
    // Iterate over the array passed in
    for (var i = 0; i < array.length; i++) {
      // Determine whether the elements of an array are still an array
      if (array[i] instanceof Array) {
        res = res.concat(flatArray(array[i])); // Continue the call to put the return values together, and then assign to the res
        // res = [...res, ...flatArray(arr[i])];
        // res = res.concat(arguments.callee(arr[i]));
      } else {
        res.push(array[i]); // Add an array}}// Return the new array
    return res;
  }
Copy the code

16.4 Implementation of array object copy (clone) (shallow copy)

An array ofArray:
1. [...arr]
2.Arr.concat () does not write the parameter array merge mode3. arr.splice(0) / arr.substring(0) / arr.substr(0Array interceptor objectObject:
1.{... obj}2. Object.assign(obj) Object merge modeCopy the code

16.5 Implementing Deep Clone (Deep Copy) for Objects

let sons = ['xelloss'.''s '.'tsao chung'];
let sister = { name: 'Cao Qin'.age: 18 };

  const obj = {
    name: "Cao cao.age: 100,
    sons,
    sister,
    say() {},
    eat(){}};// 1. With the help of JSON, there is no copy method, suitable for pure data objects
  // JSON.parse(JSON.stringify(obj));

  // 2. Use recursive functions to implement deep cloning
  let obj1 = deepClone(obj);
  obj1.sister.name = 'Cao Xueqin';
  console.log(obj);
  console.log(obj1);

  // Define a function to get the name of the constructor (class) of the object
  function getObjectClass(obj) {
    return Object.prototype.toString.call(obj).slice(8, -1);
  }

  // Deep copy function
  function deepClone(obj) {
    // Check whether obj is an object, an array or something else
    if (getObjectClass(obj) === 'Object') {
      var res = {}; // Create an empty object
    } else if (getObjectClass(obj) === 'Array') {
      var res = []; // Create an empty array
    } else {
      return obj;
    }

    // Iterate over the passed object
    for (let i in obj) {
      res[i] = deepClone(obj[i]);
    }
    // Return a new array or object
    return res;
  }
Copy the code

16.6 Methods of Traversing object properties

1. for.inIterating over itself and the properties on the stereotype that can be iterated over. Attribute names of type symbol are not allowed2. ObjectThe keys (),ObjectThe value (),Object".entries() is a property of its own, and the property name is symbol type.3. Object.geTownPropertyNames () is a collection of its own property names. A property name of type symbol is not allowed4. ObjectA collection of property names of type Symbol when.geTownPropertySymbols () has its own property name5.Reflec.ownkeys () is a collection of all of its property names (both strings and symbols are allowed)Copy the code

16.7 Promise object

// Promise object state: Success -> Fires the first callback to then
// Promise object state: failure -> Triggers the second callback to then

// then(onFulfilled, onRejected)
// Two functions are passed, and only one of them will be executed

// By default, the then method returns a success status PROMISE object
// When will a promise object return with a failed state?
// 1. The return value of the function in the method is a promise object with a failed state
// 2. Method error
// In addition to the above two methods, the default is a successful promise

const promise = new Promise((resolve, reject) = > {
  // Synchronous invocation
  resolve();
  // reject();
  console.log(111);
});

promise
  .then(
    () = > {
      console.log(222);
    },
    () = > {
      console.log(333);
      // Return a failed promise object
      // return Promise.reject();
      return new Promise((resolve, reject) = > {
        reject();
      });
      / / an error
      // Throw an exception (immediately generates an error)
      // throw 'error';
    } // By default, a success status promise object is returned
  )
  // Which is the next then to trigger? The last "THEN" returns the promise state
  .then(
    () = > {
      console.log(444);
    },
    () = > {
      console.log(555); });console.log(Awesome!);
Copy the code

16.8 Other states of the Promise object

  // Promise an asynchronous programming solution
  // Use: to solve the asynchronous callback hell problem (eliminate callback functions and express asynchronous code synchronously)

  / / features:
  / / state:
  // 1. Pending Initialization state
  // 2
  // 3

  / / note:
  // There can only be one state at a time
  // You can only change from the initialization state to the success/failure state
  // Success cannot become failure, and failure cannot become success
  // (the state is initialized as pending and can only be changed once, either successfully or failed)
  // How to determine the state of a promise object?
  // then() / catch()

  // Result value: internal result value (value/reason)
  // resolve(value)
  // reject(reason)
  // How to get the result value inside the promise object?
  // then((value) => {}) / await
  // catch((reason) => {})

  // How to create a Promise object?
  // New Promise() defaults to pending
  // promise.resolve () defaults to resolved
  // promise.reject () defaults to rejected

  // Other methods:
  // Promise.all([promise1, promise2...] )
  // The return value is a new Promise object. The state of the new Promise object looks at the passed promise
  // If all incoming Promise states are successful, the new promise will also succeed
  // If one of the incoming Promise states fails, the new promise immediately fails
  
  // Promise.race([promise1, promise2...] )
  // The return value is a new Promise object. The state of the new Promise object looks at the passed promise
  // Look at n promises passed in, which promise state changes first
  // The new promise has the same state as the previous promise
  
  // Promise.allSettled([promise1, promise2...] ) derived from ES11 / ES2020
  // The return value is a new PROMISE object, which must be successful
  // Promise object internal state values, containing n promise object state values passed in

  const promise11 = Promise.resolve();
  const promise22 = Promise.reject();

  console.log('Success status', promise11); This is very depressing. This is very depressing. This is very depressing.
  console.log('Failure state', promise22); Promise {
      
       : undefined}
      

  const promise1 = new Promise((resolve, reject) = > {
    setTimeout(() = > {
      reject(111);
    }, 1000);
  });

  const promise2 = new Promise((resolve, reject) = > {
    setTimeout(() = > {
      reject(222);
    }, 2000);
  });

  const promise3 = new Promise((resolve, reject) = > {
    setTimeout(() = > {
      reject(333);
    }, 3000);
  });

  // Only all success is successful, as long as there is a failure is a failure
  // Promise.all([promise1, promise2, promise3])
  // .then(value => {
  // console.log(" success ", value);
  / /})
  // .catch(reason => {
  // console.log(" failed ", reason);
  / /});

  // The result is the same as the state of the promise that changed first, whether it succeeded or failed
  // Promise.race([promise2, promise1, promise3])
  // .then(value => {
  // console.log(" success ", value);
  / /})
  // .catch(reason => {
  // console.log(" failed ", reason);
  / /});

  // After all promises have been executed, return to the successful state
  Promise.allSettled([promise1, promise2, promise3])
    .then((value) = > {
      console.log('It worked', value);
    })
    .catch((reason) = > {
      console.log('Failed', reason);
    });
Copy the code

Cattle people are not trained, are their own hard work out, who are better to rely on their own, they do not want to take the initiative to learn more, only hope to use a hammer, can get all the nails, then you might as well think about how to buy a lottery 5 million, but also more practical, like collecting, do not like spray, thank ^_^