The foreword 0.

1. About the content of the article

This tutorial is based on the author’s own summary after watching B station Up host @it peak broadcast, video address: vue3.x IT peak broadcast

Self-defined as literacy article, its content is not complete (of course, except the official documents or all written according to the official documents can not be called complete)

It covers some common knowledge points, which you can read before studying ES6 in a comprehensive and systematic way, or supplement for those who are not familiar with ES6

Due to the vast majority of the content by the author’s hand, it is inevitable that there will be some mistakes or flaws, or because of the different direction of understanding caused by mistakes, please correct

2. About the topic of the article

For the convenience of reading, this article uses the theme of Juejin, if uncomfortable, please understand

1. let and const

1. let

  1. Let is used to declare variables

  2. There are local scopes

    {
        let a = 10;
    }
    console.log(a);// A cannot be accessed
    Copy the code
  3. Variables declared by let will not be promoted

    console.log(a); // A cannot be accessed
    let a = 10;
    Copy the code

2. const

  1. Const is used to declare constants

    const name = 'Joe';
    // name = 'name '; // error,const declared constant, cannot be changed again
    Copy the code
  2. Constants declared by const are also not promoted

    console.log(name); // Name cannot be accessed
    const name = 'Joe';
    Copy the code
  3. When const declares an object, the object cannot be changed, but its contents can be changed

    const person = {
        name:'Joe'.age:18
    };
    console.log(person);
    // person = {} // Error, object cannot be replaced
    person.age = 19;
    console.log(person);    // No error is reported and age is changed to 19
    Copy the code

2. Arrow function

1. Use method

  1. Remove the function keyword and add => between arguments and function blocks.

    function myfunction(x){
          return x*x
      }
      console.log(myfunction(3))    / / output 9
    
      const myFunc =(x) = >{return x * x}
      console.log(myFunc(3))    / / output 9
    
    Copy the code
  2. If there is only one argument, you can remove the parentheses (note the () placeholder if there is no argument)

    const myFunc = x= >{return x * x}
    console.log(myFunc(3))  / / output 9
    Copy the code
  3. If there is only one return statement, you can remove return and {}.

    const myFunc = x= > x * x
    console.log(myFunc(3))  / / output 9
    Copy the code
  4. The arrow function must add one () to the outer layer of the object when returning it.

    const fun = id= >{({id:id, name:'Joe'})}
    console.log(fun(10).name)
    
    // Equivalent to:
    //const fun = id=>{ 
    // return ({id:id, name:' zhang SAN '})
    / /}
    // Because the object has {}, it is impossible to tell if this is an object (variable) or the body of a function without enclosing it
    Copy the code
  5. The arrow function doesn’t have its own this, its this inherits from its parent, that is, the arrow function’s this points to the object on which the arrow function is located


3. Advanced methods for adding arrays

Three methods:

  1. filter()
  2. map()
  3. reduce()

They’re going to take a function, and they’re going to execute that function as many times as the array is long as they’re going to loop through the array and apply that function to each element of the array

1. The filter () filtering

    // Takes a function that takes one argument representing each element of the loop
    let myArray=[1.2.3.4.5.6.7.8.9];

    / / filter () filter
    let array1 = myArray.filter(function(n){
        return n>5; // n loops through the array, if n is greater than 5, otherwise ignored
    })
    console.log(array1) / / 6,7,8,9
Copy the code

2. map()

    // Take a function, again with an argument, which is equivalent to applying the function's rules to each element of the array

    / / the map () mapping
    let array2 = array1.map(function(n){
        return 2*n;     // Take each element *2 and add them together to return an array
    })
    console.log(array2)     // 12, 14, 16, 18

Copy the code

3. reduce()

// Take two arguments,
// The first argument is a function that takes two arguments (s,n). The first argument represents the starting value and the second argument represents each element of the loop array
// The second argument specifies the starting value s for the first argument of the first function argument
// s refers to the last return value
// n represents the array value of the loop each time

/ / summary
let sum = 0;
sum = array2.reduce(function(s,n){
    return s+n;
},0)    // Start at 0, that is, s=0

// For the first time, s=0, n is the first value of the array 12, return 0+12,
// The second time, s is the last return value, i.e. 0+12=12, n is the second value of the array, 14, return 12+14
// The third time, s is 12+14=26, n is the third value of array 16, return 26+16
/ /... And so on
console.log(sum)

Copy the code

4. Map and Set data structures

Temporarily not updateCopy the code

5. String Added method and template strings

1. New string method

1. startswith(string)

String.startswith(String) Checks whether String begins with String and returns true or false

let url='www.baidu.com';
if(url.startsWith('https')) {console.log(url)
}else{
    console.log('Not a URL that starts with HTTPS')}Copy the code

2. endswith(string)

String.endswith(String) Checks whether a String ends in a String

if(url.endsWith('.com')) {console.log(url)
    }else{
        console.log('Not a url that ends in dot com.')}Copy the code

2. Template string

An enhanced version of a string

  1. You can write whatever you want in it, what you write is what you get, unlike a regular string that requires a special character for a line break, which requires quotation marks
// Note that the template string does not use quotation marks (single or double), but the key above the TAB key in the upper-left corner of the keyboard
let str = ` first second third something anything `
Copy the code
  1. You can introduce other variables into a string instead of writing it as string + variable + string, as normal strings do
let name = 'zhangsan';
let age = 10;

// Zhangsan is 10 years old
let normalStr = name+ ' is ' + age + ' years old';
let templateStr = `${name} is ${age} years old`

Copy the code

6. Deconstruct assignments

  1. For a normal array

let arr = [1.2.3];

// If you want to assign three values of this array to three variables:
{
    let a = arr[0];
    let b = arr[1];
    let c = arr[2];
}
// This is troublesome

// Add simple method:
{
    let [a, b, c] = [1.2 ,3];
}
// Or write:
{
    let [a, b, c] = arr;
}
Copy the code
  1. For the object
let person = {
    name:'zhangsan'.age:10.gender:'male'
}
{
    let {name, age, gender} = person;
    console.log(name, age, gender)
    // Outputs zhangsan 10 male
}
Copy the code
  1. If it is an object, the variable name on the left must be the same as the variable name on the right, otherwise it fails and remains undefined
{
    let {anotherName, age, gender} = {name:'zhangsan'.age:10.gender:'male'};
    console.log(anotherName, age, gender)
    // undefined 10, male
}
Copy the code
  1. The value to the left of a normal value can be less than the value to the right, and the values are assigned in order
let arr = [1.2.3];
{
    let [a, b] = arr;
    console.log(a,b);   / / 1. 2
}
Copy the code
  1. The object lvalue can also be less than the right-hand value, and the order can be changed because the object is assigned by key name
let person = {
    name:'zhangsan'.age:10.gender:'boy'
}
{
    let {gender, age} = person;
    console.log(gender, age)    // boy 10
}
Copy the code
  1. The compound assignment
let arr = [{name:'zhangsan'.age:10},1.2.3].'hello'.9 ];
{
    let [a,b,c,d] = arr;
    console.log(a);
    console.log(b,c,d);
}
Copy the code
  1. Decomposition of the assignment
let arr = [{name:'zhangsan'.age:10},1.2.3].'hello'.9 ];
{
    let[{name,age},[a,b,c],d,e] = arr;
    console.log(name,age);  // zhangsan 10
    console.log(a,b,c);     / / 1 2 3
    console.log(d,e);       // hello 9

}
Copy the code
  1. Declaration and assignment are inseparable
let [a,b];  Let [a,b] = arr;

Copy the code

7. Three-point extension operator

1. Expand arrays

  1. Array1 goes to the front end of myArray, array2 goes to the back end of myArray
let array1 = [1.2.3];
let array2 = [7.8.9];
let myArray = [...array1, 4.5.6. array2] ;console.log(myArray)    // 1, 2, 3, 4, 5, 6, 7, 8, 9
Copy the code
  1. When each element of an array is an argument, you can use the three-point extension operator to deconstruct the array
function myFunction(a, b, c) {
    console.log(a,b,c);     
    return a+b+c;
}
let arr = [1.2.3];
console.log(myFunction(... arr));/ / 1 2 3
/ / 6
Copy the code
  1. The argument list is converted to an array using the three-point extension operator

We learned from 2 that passing an argument to a three-point operator converts the elements of an array into separate variables. So if a parameter uses a three-point operator and the argument is passed to a separate variable, does that make it an array in a function?

function myFunction(. arr) {
    for(let i = 0; i <arr.length; i++)
    {
        console.log(arr[i]);
    }
    console.log(arr);
}
myFunction(3.12.45.123);
/ / 3
/ / 12
/ / 45
/ / 123
// 3 12 45 123
// This is a good idea
Copy the code
  1. Part of the parameter uses a three-point extension operator
function myFunction(a,b, ... arr){
    console.log(arr);
}
myFunction(1.2.3.4.5.6.7);  // 3 4 5 6 7
// 1, 2 is assigned to a, b, and the rest generates the array arr
Copy the code

8. New syntax for objects

1. New class concepts

  1. Use class to create classes and constructor to create constructors
/ / create the class
class Person {
    // Create a constructor
    constructor(name, age, gender){
        this.name = name;
        this.age = age;
        this.gender = gender; }}Copy the code
  1. Methods in a class do not need the keyword function
/ / create the class
class Person {
    // Create a constructor
    constructor(name, age, gender){
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    // Create a class method
    say() {
        console.log(this.name+' '+this.age+' '+this.gender); }}Copy the code
  1. Use new to create an instance of the class and pass in parameters (if any)
/ / create the class
class Person {
    // Create a constructor
    constructor(name, age, gender){
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    // Create a class method
    say() {
        console.log(this.name+' '+this.age+' '+this.gender); }}// Create an instance of the class
let person1 = new Person('zhangsan'.18.'male')
    
Copy the code
  1. Using methods in objects, etc., using the. Operator
/ / create the class
class Person {
    // Create a constructor
    constructor(name, age, gender){
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
    // Create a class method
    say() {
        console.log(this.name+' '+this.age+' '+this.gender); }}// Create an instance
let person1 = new Person('zhangsan'.18.'male');
// Call say()
person1.say();  // zhangsan 18 male
Copy the code
  1. Extends extends from a parent class, and all parent properties and methods are inherited
class Person {
    // Create a constructor
    constructor(name, age, gender){
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
    // Create a class method
    say() {
        console.log(this.name+' '+this.age+' '+this.gender); }}class Students extends Person {

}
student1 = new Students('lisi'.19.'male'.'8003119501')
console.log(student1.name)  // lisi
student1.say();             // lisi 19 male
student1.age = 20;          // Change the age
student1.say();             // lisi 20 male
Copy the code
  1. Subclasses of super() can use the constructor of the parent class. By default, the constructor of the parent class is used. Adding constructor(){} overrides the constructor of the parent class
class Person {
    // Create a constructor
    constructor(name, age, gender){
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
    // Create a class method
    say() {
        console.log(this.name+' '+this.age+' '+this.gender); }}class Students extends Person {
    construtor(){
        // Given a subclass constructor without any implementation, the parent class constructor is overridden}}// Error, Students given their own constructor but not implemented
student1 = new Students('lisi'.19.'male'.'8003119501')
     
Copy the code
  1. Use super() to simplify the constructor of subclasses
class Person {
    // Create a constructor
    constructor(name, age, gender){
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
    // Create a class method
    say() {
        console.log(this.name+' '+this.age+' '+this.gender); }}class Students extends Person {
    construtor(name, age, gender, id){
        super(name, age, gender);   // Assign name,age,gender using the superclass method
        // This is equivalent to:
        // this.name = name;
        // this.age = age;
        // this.gender = gender;
        // Use super() directly in this case to simplify things

        // Add the new id attribute
        this.id = id;
    }
}

student1 = new Students('lisi'.19.'male'.'8003119501')
console.log(student1);
// All four attributes are created and passed in initial values
// Students
// age: 19
// gender: "male"
// id: "8003119501"
// name: "lisi"
// __proto__: Person

// But calling the inherited say() method only outputs the first three attributes, because the inherited method is the same as the parent, and the parent's say() method does not output an ID
student1.say();     // lisi 19 male
Copy the code
  1. Override the parent class method
class Person {
    // Create a constructor
    constructor(name, age, gender){
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
    // Create a class method
    say() {
        console.log(this.name+' '+this.age+' '+this.gender); }}class Students extends Person {
    construtor(name, age, gender, id){
        super(name, age, gender);   // Assign name,age,gender using the superclass method
        // This is equivalent to:
        // this.name = name;
        // this.age = age;
        // this.gender = gender;
        // Use super() directly in this case to simplify things

        // Add the new id attribute
        this.id = id;
    }

    // Override the parent class's say() method to output four attributes
    say(){
        // Override the inherited parent's say() method if nothing is written
        console.log(this.name, this.age, this.gender, this.id);
    }
}

student1 = new Students('lisi'.19.'male'.'8003119')
student1.say(); // lisi 19 male 8003119
Copy the code

2. json

  1. Value When using a variable, if the key name is the same as the name of the variable, it can be written as one

//
// let obj = {
// name:'zhangsan',
// age:14,
// gender:'male'
// }

// Short for special cases:
name = 'lisi';
age = 14;
sex = 'male';
let obj = {
    name,   // age = age; // age = age
    age,
    gender:sex      // The key name gender, the variable name sex, can not be shortened to one, if you defined a variable gender, you want to use sex, but use gender, if gender is not defined, error undefined
}
Copy the code
  1. Function_name :function(){}
    name = 'zhangsan';
    age = 15;
    let obj = {
        name,
        age,
        say(){
            console.log(this.name, this.age)
        }
    }

    obj.say();  // zhangsan 15
Copy the code
  1. Serialize using json.stringify ()
name = 'zhangsan';
age = 15;
let obj = {
    name,
    age
}
let str = JSON.stringify(obj);
console.log(str.name)   // undefined
console.log(str)    // {"name":"zhangsan","age":15}
Copy the code
  1. Parse () is used for deserialization
let obj = JSON.parse('{"name":"lisi","age":19}')
console.log(obj.name, obj.age)    // lisi 19
Copy the code

9. Modular programming

1. Introduction of Module

When writing HTML files, we usually introduce a number of JS files like this:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <script src="./1.js"></script>
    <script src="./2.js"></script>
    <script src="./3.js"></script>
</head>
<body>
    
</body>
</html>

Copy the code

Error 1.js and 2.js both define a variable name when there are duplicate names in these js files

// 1.js
let name = 'zhangsan';
Copy the code
// 2.js
let name = 'lisi';
Copy the code

Uncaught SyntaxError: Uncaught SyntaxError: Identifier ‘name’ has already been declared because importing js will cause browsers not to know how to parse the name variable

We can assign the type attribute of the script tag to module

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <script src="./1.js" type='module'></script>
    <script src="./2.js" type='module'></script>
    <script src="./3.js" type='module'></script> 
</head>
<body>
    
</body>
</html>
Copy the code

In this way, every JS file belongs to a module, so that no error will be reported. The same variable name belongs to different modules, so that there is a standard to distinguish

2. How to access the same variable in different JS files

Each module is closed, but we can expose its properties

// 1.js

let name = 'zhangsan';
function add(a, b){return a+b}

export {name, add};  Export {name:name}; export {name:name};
Copy the code

This exposes the name in 1.js, but to prevent other JS files from being accessible once exposed, we also have an import function called import

// 3.js

import {name, add} from './1.js';   
// Notice the use of destruct assignment, equivalent to:
// let {name, add} = {name:name, add:add} (this object comes from the./1.js file export)

// Then we can use name and add directly
console.log(name);  // zhangsan
console.log(add(3.9)); / / 12
Copy the code

3. How to resolve naming conflicts after introduction

Naming duplication can also occur when we import variables from other files

// 3.js
import {name} from './1.js';
import {name} from './2.js';
Copy the code

In this case we can use alias method

// 3.js
import {name as name1} from './1.js';
import {name as name2} from './2.js';
// Then use name1 or name2
Copy the code

You can also alias the 1.js or 2.js attribute when it is exposed

// 1.js

let name = 'zhangsan';

export {name as name1};
Copy the code
// 2.js

let name = 'lisi';

export {name as name2};
Copy the code
// 3.js
import {name1} from './1.js';
import {name2} from './2.js';

console.log(name1, name2);  // zhangsan lisi
Copy the code

4. Expose when defining properties

We can expose it when we define the property

// 1.js
export let name = 'zhangsan';
Copy the code

The attributes so exposed can still be used in this file

// 1.js
export let name = 'zhangsan';
console.log(name);  // zhangsan
Copy the code

5. Lack of name exposure attributes

Functions or classes can be exposed without naming them

// 1.js
export default function(a){
    console.log(a)
}
Copy the code

The receiving name does not need {}

// 3.js
import printa from './1.js'
// Printa is self-defined
Copy the code

Each JS file can only define one export default,

// 1.js
export default function(a){
    console.log(a)
}
export default function(a){
    return b;
}
Copy the code

If there are two or more, then like

// 3.js
import printa from './1.js'
import printb from './1.js'
/ / error:
// Uncaught SyntaxError: Identifier '.default' has already been declared

Copy the code

Such an introduction method does not know which unnamed exposure to introduce

6. Accept all exposed attributes

You can import all the exposed properties of a JS file and put them into an object for easy access

export * as name from 'url';   // Create an object to receive all exposed attributes
// name.attr;
Copy the code