I am small white, welcome correction

Let and const

Var:

  1. You can repeat the declaration
  2. Variable promotion is possible (that is, the declaration is promoted to the front)

Let:

  1. You cannot duplicate the declaration
  2. Block-level scope
  3. Variable promotion is not possible

Const:

  1. You cannot duplicate the declaration
  2. Block-level scope
  3. The statement cannot be modified
  4. Must be initialized when declared
  5. The contents of an array declared by const can be modified, so we normally use const to declare array variables

2. Deconstruct assignment

1. What is deconstruction? : ES6 allows you to extract values from arrays and objects and assign values to variables in a pattern called deconstruction

2. Array destruct assignment:

Grammar:
let[a, b, c] = [1, 2, 3]. console.log(a,b,c);Copy the code

3. Object deconstruction assignment:

Grammar:
let{a,b} = {
        a:'aa',
        b:'bb'
};

console.log(a,b);
Copy the code
Order: Data is deconstructed according to the corresponding position, but there is no order for object variables to be deconstructed. Variables must have the same name as attributes to be successfully deconstructed.
Note: Variables declared by lets and const cannot be destructively assigned!

4. String deconstruction assignment:

Grammar:
 let[a,b,c,d] = 'hello'; console.log(a,b,c,d); //h e l lCopy the code

5. Deconstructive assignment of values and Bools:

6. Function deconstruction assignment:

Grammar:
 functionfun([x,y]){ console.log(x+y); } fun ([1, 2]); / / argumentsCopy the code

7. Use of deconstruction:

  1. Swap the values of variables
  2. Return multiple values from a function (so you can call some data quickly)
  3. Function and the cords
  4. Extract JSON data (deconstruction is especially useful for extracting JSON)
  5. Function parameter defaults (ES6 allows function parameter defaults to be set)

8. Function default initial value:

General usage :(write the default value directly after the parameter)
function fun(x,y ='world'){
       console.log(x,y);
 }
Copy the code

Used in conjunction with deconstruction:

function fun({x,y=5}={}){
       console.log(x,y);
}
Copy the code
Note:
1. The length attribute of a function is the number of parameters of the function!
2. Generally with default worth parameters should be put last! (Unspoken rule)

Template string

1. The JavaScript notation:

 'He is <b>'+person.name+'</b>'+'and we wish to know his'+person.age+' . That is all.'
Copy the code

2. Template string writing:

`He is <b>${person.name}</b> and we wish know his ${person.age} . That is all.`
Copy the code

This writing method reduces a lot of complicated work!

If you need to use ‘ ‘, you can escape!

Of course, template strings can also be used without variables.

4. Simplified writing of objects

1.ES6 allows you to write variables and functions directly inside curly braces, which is often used in Vue as object properties and methods.

Arrow function

1.ES6 allows you to define functions using arrows (=>)

There are two ways to declare functions:
 let fn = function(){
 }

 let fn = (a,b) => {
 return a+b;
 }
Copy the code

2. This is static. This always refers to the value of this in the scope in which the function was declared

3. The arrow function’s this value is static, always pointing to the value of this in the scope in which the function was declared

Such as:
// General declarationfunction getName() { console.log(this.name); } // arrow functionlet getName2 = () => {
        console.log(this.name); 
 }
 window.name = 'Zhou Shiyang';
        const school = {
        name: 'zsy'} getName(); // getName2(); GetName. Call (school); //zsy getName2.call(school); / / teacher Yang zhouCopy the code

4. Arrow functions cannot instantiate objects as constructors!

5. Arrow functions cannot use arguments:

Typical incorrect usage:
 letFn = () =>{console.log(arguments)} fn(1,2,3); // An error will be reported. Arrow functions do not support argumentsCopy the code

6. Abbreviations of arrow functions:

  1. Omit the parentheses: when there is one and only one parameter
  2. Omit curly braces: when the body of the code contains only one statement

7. The arrow function is suitable for callbacks unrelated to this, such as timers, arrays, etc. It is not suitable for callbacks related to this. Does not apply to the definition of methods within an object, otherwise the scope may have problems

Rest parameters for ES6

1.ES5 uses arguments to get function arguments

Such as:
 function fn(){ console.log(arguments); // Return Object}Copy the code

2.ES5 uses rest parameters to get function arguments

Such as:
 functionFn (... args){ console.log(args); // Returns an Array object to facilitate the processing of function arguments}Copy the code
More advanced use cases:
 functionFn (a, b,... Args){// Args goes after console.log(a); //1 console.log(b); //2 console.log(args); } fn(1,2,3,4,5,6);Copy the code

Extend operators

1. “…” Ability to convert arrays into comma-separated “argument sequences”

Basic usage:
 const TFboys = ['hanah'.Jackson Yi.'Wang Junkai'];function show(){ console.log(arguments); } the show (... TFboys); // return => 'Wang Yuan', 'Yi Yangqianxi', 'Wang Junkai' character sequenceCopy the code

2. The extension operator is used to merge arrays

ES5 usage:
 const kuaizi = ["Xiao".'Wang Taili'];
 const fenghuang = ['chenrui'.'ling flowers'];
 const zuixuan = kuaizi.concat(fenghuang);
Copy the code
ES6 usage:
Const zuixuan = [fenghuang,... kuaizi]; // Use the extension operatorCopy the code

3. Extension operators are used to clone arrays

 const arr1 = ['z'.'s'.'y']; Const arr2 = arr1 [...]; / / use... forclone
Copy the code

4. Convert pseudo-arrays into real arrays

 const divs = document.querySelectorAll('div'); const divarr = [..divs]; // It has been converted to a real arrayCopy the code

Eight, Symbol

Symbol is an identifier, a type that represents a unique value

1. The Symbol’s brief introduction:

  1. The value of Symbol is unique and is used to resolve naming conflicts
  2. The value of Symbol cannot be computed with other data
  3. Object properties defined by Symbol cannot use for… in… Loop through, but you can use reflect.ownkeys to get all the key names of the object

2. Create the Symbol in two ways:

  1. Create it directly using Symbol:
 let s1 = Symbol('zsy');
 let s2 = Symbol('zsy'); console.log(s1 === s2); //falseNotice that this is not equal!Copy the code
  1. Create it using symbol.for
 let s1 = Symbol.for('zsy');
 let s2 = Symbol.for('zsy'); console.log(s1 === s2); //trueSo it's equal!Copy the code

3. Use of Symbol

Add methods (function) securely using Symbol:
 let game = {}
 let methods = {
        up:Symbol(),
        down:Symbol()
 }
 game[method.up] = function(){
        console.log('1');
 }
 game[method.down] = function(){
        console.log('1');
 }
Copy the code
Add methods (internal) in another case:
let youxi = {
       name:'Werewolf Kill',
       [Symbol('say')]:function(){
               console.log('I can say! '); }}Copy the code

4. Symbol’s built-in method, you can view the document by yourself

Iterators

1. The for… The in… : Traversal returns the key nameThe for… Of… : Traversal returns key values

2. How iterators work

  1. Creates a pointer object that points to the start of the current data structure
  2. The first time the object’s next method is called, the pointer automatically points to the first member of the data structure
  3. The next method is used repeatedly, moving the pointer backward until it points to the last data member
  4. Each time the method is called, an object containing the value and done attributes is returned (done is done, a Boolean, true if traversal is complete, false otherwise).

3. Note: When customizing traversal data, think iterators!

Custom traversal data code example:
 const stu = {
        name: "zsy",
        stus: [
                'xiaoming'.'xiaoning'.'xiaotian'.'knight'], [symbol.iterator]() {// Must have iterator objectslet index = 0;
                let_this = this; / / save thisreturn {
                        next: function() {
                        if (index < _this.stus.length) {
                                const result = {
                                        value: _this.stus[index],
                                        done: false
                                };
                                index++;
                                return result;
                        } 
                        else {
                                return {
                                        value: undefined,
                                        done: true
                                };
                        }
                 }
        }
        }
 }
 
 for (let v of stu) {
        console.log(v);
 }
Copy the code

X. Generators

1. Generators are a special function that is often used for asynchronous programming

Introduction to generator functions:
 function * gen() {// Special notation for generator functions, note that * console.log()'hello zsy! ');
 }

 letite = gen(); // console.log(ite); // This is an error, and it does not run the generator function ite.next(); // This is the correct way to write, execute statementCopy the code

2. Yield keywords are allowed in generator functions (yield keywords: used to separate blocks of code, executing code in two yields at a time)

Example:
 function * gen() {
        console.log('1');
        yield 'I am 1';
        console.log('2');
        yield 'I am 2';
        console.log('3');
        yield 'I am 3';
        console.log('4');
 }

 letite = gen(); ite.next(); //1 ite.next(); //2 ite.next(); //3 ite.next(); / / 4Copy the code

3. Generator functions can use for… Of… To traverse the

 function * gen() {
        yield 'I am 1';
        yield 'I am 2';
        yield 'I am 3';
 }

 for(letv of gen()){ console.log(v); } //I'm 1 //I'm 2 //I'm 3Copy the code

4. The next function can be passed parameters, which can be printed as the value after the next yield.

5. Examples of generator functions: (asynchronous programming: helps to avoid callback hell (indentation stretching forward out of the edit area is bad for reading and maintenance)

(Using timer implementation)
 function one() {setTimeout(()=>{ console.log(111); ite.next(); 1000}}},function two() {setTimeout(()=>{ console.log(222); ite.next(); 2000}}},function three() {setTimeout(()=>{ console.log(333); ite.next(); 3000}}},function *gen(){
        yield one();
        yield two();
        yield three();
 }

 letite = gen(); ite.next(); // This implements asynchronous outputCopy the code
(Realize the simulation process of data acquisition)
(Asynchrony is real life)
 function getUsers() {setTimeout(()=>{
                let data = 'User data'; ite.next(data); }}, 1000)function getOrders() {setTimeout(()=>{
                let data = 'Order data'; ite.next(data); }}, 1000)function getGoods() {setTimeout(()=>{
                let data = 'Commodity data'; ite.next(data); }}, 1000)function * gen() {let users = yield getUsers();
        console.log(users); 
        let orders = yield getOrders();
        console.log(orders);
        let goods = yield getGoods();
        console.log(goods);
 }

 let ite = gen();
 ite.next();
Copy the code

Promise in ES6

1. Promise is a new asynchronous programming solution introduced in ES6. Syntactically, promise is a constructor that encapsulates asynchronous operations and can capture the results of their success or failure

2. Simple Promise use cases

 const p = new Promise(function(resolve,reject){// Use resolve and rejectsetTimeout(function() {let data = 'Data in database'; resolve(data); // Use case on success, return data as valuelet err = 'Data read failed'; reject(data); // Use case for failure, return data as reason},1000)}); p.then(function(value){// Common value and reason console.log(value); },function(reason){
        console.error(reason);
 })
Copy the code

3. Use the Promise wrapper to read the file

Example:
 const fs = require('fs'); // Use node.js require to introduce the require module const p = new Promise(function(resolve,reject){
        fs.readFile('./demo,md',(err,data)=>{
        if(err) reject(err); Resolve (data); // Success}); }); p.then(function(value){
        console.log(value.toString());
 },function(reason){
        console.log('Read failed! ');
 });
Copy the code

4. Wrap Ajax with Promise

Example:
Const p = new Promise((resolve,reject)=\>{// Create a Promise const XHR = new XMLHttpRequest(); // Create a new XMLHttpRequest object xhr.open(' GET ', 'https://... '); // use the GET method xhr.send(); // Send the request xhr.onreadyStatechange =function(){// The onchange event is raised when the state changesif(xhr.readyState === 4){// If the state is 4, the request has been responded and the last stage has been reachedif(xhr.status >= 200&& xhr.status < 300){// Resolve (xhr.response); // Call the response method}else{ reject(xhr.status); // call reject method}}}}); p.then(function(value) {/ / usethenMethod on the state of the Promise object console.log(value); },function(reason){ console.error(reason); // Use error to warn the console})Copy the code

5. The prototype of a promise is then.

  1. The result of the then method is a Promise object
  2. If the return is a non-promise property (return ‘zsy’), the value is zsy
  3. If the return is a promise property (return New Promise ()), the next resolve or reject value
  4. Throw new Error (‘ Error! ‘)), the value is error, and reject is automatically called

6. Read the contents of multiple files asynchronously using the Promise method

Example:
 const fs = require('fs'); Const p = new Promise((resolve, reject) => {fs.readfile ())'./demo.md', (err, data) => {
                resolve(data);
        });
 });

 p.then(value => {
        returnNew Promise((resolve, reject) => {// Return new Promise object fs.readfile ('./demo2.md', (err, data) => { resolve([value, data]); })}). Then (value => {returnNew Promise((resolve, reject) => {// Return new Promise object fs.readfile ('./demo3.md', (err, data) => {
                        value.push(data);
                        resolve(value);
                })
        })
 }).then((value => {
        console.log(value.join('\r\n')); }))Copy the code

7. The catch method in promise (which is a syntactic candy)

Usage:
 p.catch(function(reason){
        console.error(reason);
 })
Copy the code

Xii. Collection

1. Sets are similar to arrays, but each element is unique (the elements are not allowed to duplicate).

For traversal, also built in some API, you can look at the documentation to learn

2.Set can be used for array deduplication

 let,2,3,2,1,2,3 arr = [1];letResult = new Set (arr) [...];Copy the code

3.Set can be used to find intersection, union and difference sets

/ / intersectionlet,2,3,2,1,2,3 arr = [1];let,2,1,1 arr2 = [1];letThe result = [... new Set(arr)]. Filter (item=\>{//filter method tests all elements with the specified function and creates a new array containing all elements that pass the test.let s2 = new Set(arr2);
        if(s2.has(item)){
                return true;
        }
        else{
                return false; }}); / / and setletThe union = [... new Set ([arr1, arr2])]; / / difference setletdiff = [..new Set(arr)].filter(item=>! new Set(arr2),has(item));Copy the code

13, the Map

1.Map is a collection of key-value pairs, but keys are not limited to strings. They can be any type of value. Of… To traverse the

Simple Map usage
 let m = new Map();
 m.set('change'.function() {the console. The log (' I am zsy. '); });let key = {
        school:'XDU'}; m.set(key,['South Campus'.'North Campus');
 console.log(m.size);
 console.log(m.get('change'));
 console.log(m.get(key));
 m.delete('change');
Copy the code

Class

1. Class can declare a class as a template for an object (which is also a syntax sugar)

Simple use
// Use ES5 methods to instantiate objects via constructorsfunction Phone(brand,price){
        this.brand = brand;
        this.price = price;
 }

 Phone.prototype.call = function()
        console.log('I can call! ');
 }

 let HuaWei = new Phone('huawei',5999) HuaWei.call(); console.log(HuaWei); Constructor (constructor){this.brand = brand; // Constructor (constructor){this.brand = brand; this.price = price }call(){// the method must use the call method, not the call:functionConsole.log ()'I can call! '); }}let onePlue = new Phone('one plus', 5999); console.log(onePlus);Copy the code

2. The class has static members

usage
 class Phone{
        static name = 'mobile phone';
         static change(){
            console.log('I can change the world! '); }}letnokia = new Phone(); console.log(nokia.name); //Undefined console.log(Phone.name); // phone // indicates that static members belong only to the class and not to the instantiated objectCopy the code

3. The class inheritance

// Constructor inheritance in ES5function Phone(brand,price){
        this.brand = brand;
        this.price = price;
 }
 Phone.prototype.call = function(){
        console.log('I can make a phone call');
 }
 function SmartPhone(brand,price,color,size){
        Phone.call(this.brand,price);
        this.color = color;
        this.size = size;
 }

 SmartPhone.prototype = new Phone;
 SmartPhone.prototype.constructor = SmartPhone;
 SmartPhone.prototype.photo = function(){
        console.log('I can take pictures');
 }
 SmartPhone.prototype.playGame = function(){
        console.log('I can play games');
 }
 
 const chuizi = new SmartPhone('hammer', 3999); // Instantiate the object console.log(chuizi); Class Phone{constructor(brand,price){this.brand = brand; this.price = price; }call(){
                console.log('I can call! '); }} Class SmartPhone extends Phone{constructor(brand,price,color,size){super(brand,price); // use super}photo(){
                console.log('photos');
        }
        play(){
                console.log('Play the game')
        }
 }
 const xiaomi = new SmartPhone('millet', 799,'black'.'4.7 inch);
 console.log(xiaomi);
Copy the code

4. Subclass overrides the parent class

// Write the same parent method in the subclassCopy the code

5. Get and Set in ES6

Simple use case
  class Phone{
        get price(){// Each call to the price member is customized with the get method console.log(' The price attribute is read! ');return '11'; // Return value of price member}setPrice (newVal){// Note that the get method must take one argument and is called every time the price member's value changessetMethods the console. The log ('Price attribute modified! '); }}lets = new Phone(); // Instantiate the object console.log(s.price); // The price attribute is read! //undefinedCopy the code

Numerical extension in ES6

1.Number.EPSILON represents the minimum precision (16 decimal places) in JavaScript

Use cases:
  function equal(a,b){
            if(Math.abs(a-b) < Number.EPSILON){
                    return true
            }else{
                    return false;
            }
  }

  console.log(0.1+0.1 === 0.3);//falseThe console. The log (equal (0.1 + 0.2, 0.3)); //true
Copy the code

Binary and octal

Use cases:
  leta = 0b0101; / / binaryletb = 0o777; / / octalletc = 100; / / decimalletd = 0xff; // HexadecimalCopy the code

3. Determine whether a finite Number is used

4.Number.isNaN checks whether a Number isNaN

5.Number.parseIntNumber.parseFloat Turns a string to an integer

6.Number.isInteger Checks whether a Number is an integer

7.Math.trunc Erasures the decimal part of a number

8.Math.sign determines whether a number is positive or negative or zero

ES6 object method extension

1.Object.is Checks whether two values are completely equal

Simple use case
console.log(Object.is(NaN,NaN)); Console. log(NaN,NaN); // Using the equal sign, two nans are not equalCopy the code

2. Merge object. assign objects

    const config1 = {
            host:'localhost',
            port:3306,
            name:'zsy',
            pass:'zsy'
    }

    const config2 = {
            host:'localhost2',
            port:3306,
            name:'root',
            pass:'root'} console.log(Object.assign(config1,config2)); Config1 is overwritten by config2. If an element is present in 1 but not in 2, it is added directly to 2Copy the code

3.Object.setPrototypeofObject.getprototypeof sets and obtains prototype objects

ES6 modularity

1. Help to deal with conflicts between modules, easy to maintain, easy to modify

2. The main modular specifications before ES6 are:

AMD => requireJ 3. CMD => seaJS 2Copy the code

3. The modularization function consists of two commands: export and import

1) The export command is used to specify the external interface of the module. 2) The import command is used to input functions provided by other modulesCopy the code

4. Modular simple use cases:

// Three exposed methods //index.html <scripttype='module'>
            import * as m1 from './src/js/m1.js'; Import * as m2 from'./src/js/m2.js';
            import * as m3 from './src/js/m3.js'; 
            console.log(m1);
            console.log(m2);
    </script>
    
    //m1.js
    export let school = 'XDU'; / / useexportExposed data, exposed separatelyexport function teach(){
            console.log('I'm zsy! ');
    }
    
    //m2.js
    let school = 'zsy';
    function findJob(){
            console.log('hahaha');
    }
    export{school,findJob}; // unified exposure //m3.jsexportDefault {// Default exposurelet school = 'XDU';
    }
Copy the code

5. Mode of importing modules

// Import * as m1 from'./src/js/m1.js'; Import * as m2 from'./src/js/m2.js';
    import * as m3 from './src/js/m3.js'; Import {school,teach} from'./src/js/m1.js';
    import {school as guigu,findJob} from './src/js/m2.js'; // Import {default as m3} from is not often used for default exposure'./src/js/m3.js'; Import m3 from import m3 from import m3 from import m3 from import m3 from'./src/js/m3.js'
Copy the code

6. Browsers use modularity in two ways

  1. Import using import
  2. Create an entry file and import only the entry file directly

ES6 uses Babel to transform modular code

1. Install Babel. You can learn more about it

Simple steps:
  1. Installation tool: babel-cli babel-preset-env Browserify (or webpack)
  2. NPX Babel SRC /js -d dist/js
  3. NPX Browserify dist/js/app.js(source path) -o dist/bundle.js(destination path)
  4. Each update is reconverted and packaged

19, ES6 modular introduction of NPM package

1. Download and install the package

2. Import variable name from ‘path’;