ES6 summary

// Most of the following content is summarized from the in-depth interpretation of ES6 series (all 18 lectures), the most popular one

1.

babel == browser.js

<script arc="browser.js" charset="-8"></script> <script type= "text/ Babel ">Copy the code

2.

In JS, var: can be declared repeatedly; Unable to restrict changes; There is no block-level scope

In ES6, let: cannot be declared repeatedly; Variable values can be modified; There is block-level scope; There is no variable promotion; There are temporary dead zones

In ES6, const: cannot be repeated; Variable values cannot be modified; There is block-level scope; There is no variable promotion

3. Const objects freeze

Normal a const object

const person = {}; Person. Name = "aaa"; Person.age = 26; person.age = 26; console.log(person.name); //aaa console.log(person.age); //26 console.log(person); / / Object {name: "aaa", the age: 26} person = {name: "BBB"}; //person is a const object and cannot be modifiedCopy the code

Const freeze

const person = Object.freeze({}); Person. Name = "aaa"; Person. age = 26; person.age = 26; console.log(person.name); //undefined console.log(person.age); //undefined console.log(person); //ObjectCopy the code

It can only be written in the following form

Const person = object. freeze({name: "aaa"; age:26; }); console.log(person.name); //aaa console.log(person.age); //26 console.log(person); //ObjectCopy the code

// Since a const object may be an object inside, it needs to be completely frozen

"// Freeze the program var constantize = (obj) =>{object.freeze (obj); Object.keys(obj).foreach (key,value) => {if(typeof obj[key] === 'Object'){constanj (obj[key]); }}};Copy the code

4. Cross-module constants

With export and import

5. Deconstruct assignments

1. The left and right sides of the equal sign must have the same structure;

2. The right hand side must be something (see the first example below);

3. Declaration and assignment cannot be separated and must be done in one sentence.

Let [a, b, c] = [1, 2, 3]. / / an array of the console, log (a, b, c); //1 2 3 let {a,c,d} = {a:12, c:5, d:6}; //JSON console.log(a,c,d); / / 12 5 6Copy the code

Object structure assignment. When specifying the default value, the default value takes effect only if the attribute value of the object is strictly equal to undefined and the deconstruction failure value is undefined

var {x = 3} = {x:undefined}; console.log(x); //3 var {y = 3} = {y :null}; // Console.log (y) does not meet the default setting. //nullCopy the code
var x; {x} = {x:1}; // The JS engine interprets {x} as a code block, but this code block does not declare console.log(x); / / an errorCopy the code

// Add a ()

var x; ({x} = {x:1}); console.log(x); / / 1Copy the code

Existing object methods

console.log(Math.sin(Math.PI/6)); //0.4999999999994 let {sine, cosine, tan} = Math; console.log(sin(Math.PI/6)); / / 0.49999999999994Copy the code

Destruct assignment of a string

Const [a, b, c, d, e] = "hello"; console.log(a); //h// the string can be treated as an array console.log(b); //eCopy the code
Const {length: len} = "hello"; console.log(len); Const {length} = "hello"; const {length} = "hello"; console.log(length); / / 5Copy the code

Destruct assignment of function arguments

function sum([x,y]){ return x + y; } the console. The log (sum ([1, 2])); / / 3Copy the code

Function arguments destruct the default value of assignment

function fun({x = 0, y = 0} = {}){ return [x, y]; } console.log(fun({x:100, y:200})); //[100, 200] console.log(fun({x:100})); //[100, 0] console.log(fun({})); //[0, 0] console.log(fun()); / / [0, 0]Copy the code

The default value of function argument destruct assignment is undefined

Function fun({x, y} = {x:0, y:0}){//{x,y} is just a declaration variable, which depends on the argument return [x, y]; } console.log(fun({x:100, y:200})); //[100, 200] console.log(fun({x:100})); //[100, undefined] console.log(fun({})); //[undefined, undefined] console.log(fun()); //[0, 0]// By default, destruct assignment is not done in function parameters, but in objectsCopy the code

The purpose of deconstructing assignment:

Swap values of variables; Return multiple values from a function; Definition of function parameters; Extract JSON data; Default values for function arguments; Traversal Map structure; Specifies the method of input module

Arrow function

1. If there is only one parameter, () can be omitted;

2. If there is only one return statement, {} and return can be omitted

7. Function parameters

1. Parameter expansion/array expansion

Parameters (a, b,… Args)// Args is an array representing the Rest Parameter, which must be the last Parameter, (a,b,… The args, c) is wrong

1.1 Collecting Remaining Parameters

function show(a,b,… args){}

1.2 Expanding an Array

Let arr = [1, 2, 3];

. Arr // stands for 1,2,3. If I expand it, it’s going to look like I just wrote the contents of the array here;

Note: assignments like the one below cannot be used. Any other assignment can be used

let a; Let arr = [1, 2, 3]; a = ... arr; // This assignment is used incorrectlyCopy the code

2. Default parameters

function show(a, b = 5, c = 12){…… }

An array of 8.

Map: one to one;

Reduce: to come out of a pile;

The filter filter

ForEach loop/iteration

map

Let arr =,2,5,8 [1]; Let result = arr.map(function(item){return item*2; }); alert(result);Copy the code

The above code can be abbreviated as:

let result = arr.map(item=>item*2);
Copy the code

reduce

Let arr =,69,180,8763 [12]; Let result = arr.reduce(function(temp,item,index){//temp is the intermediate result,item is the next parameter, Alert (temp + ', '+ item +', '+ index)}); //undefined,180,2 //undefined,8763,3Copy the code
Let arr =,69,180,8763 [12]; let result = arr.reduce(function(temp,item,index){ return temp + item; }); alert(result); //9024 //12 69 =>81 //81 180 =>261 //261 8763 =>9024Copy the code

filter

Let arr =,5,8,99 [12]; Let result = arr.filter(item => if(item % 3 ==0){return true; }else{ return false; } ) alert(result); {return item % 3 ==0}; return item % 3 ==0}; // let result = arr.filter(item => item % 3 ==0);Copy the code

forEach

Let arr =,5,8,9 [12]; arr.forEach(item =>{alert(item)}); / / 12,5,8,9 arr. ForEach ((item, index) = > {alert (index + ":" + item)});Copy the code

9. The string

1. Two new approaches

StartsWith to… At the beginning

EndsWith. To… At the end

Let the STR = "lixinS319070033. Making. IO"; The console. The log (STR. StartsWith (" lixin ")); //trueCopy the code

2. String template

Insert something directly into a string, which is enclosed in backquotes, ${stuff}

Can fold line

let a = 12;
let str = `a${a}bc`;
alert(str); //a12bc
Copy the code

Fold line

Let title = 'title'; Let content = 'content'; let str = `<div> <h1>${title}</h1> <p>${content}</p> </div>`;Copy the code

10. Object oriented

1. Constructor is separated from class

2. Add objects directly to class

class User{ constructor(name,pass){ this.name = name; this.pass = pass; } showName(){ alert(this.name); } showClass(){ alert(this.pass); }}Copy the code

inheritance

Class VipUser extends User{constructor(name,pass,level){constructor(name,pass,level){superclass == super(name,pass); this.level = level; } showLevel(){ alert(this.level); }} var v1 = new VipUser(' blue ', '123456', 3); v1.showName(); v1.showPass(); v1.showLevel();Copy the code

React relies heavily on ES6

React:

1. Modularization/componentization — class

2. Strongly dependent on JSX==babe==browser.js

11.JSON

1. A JSON object

Let json = {" a ":12," b ":5}; Let STR = 'ABC' + json; alert(str); //abc[object Object]Copy the code

or

Let STR = 'ABC' + json.stringify (JSON); / / ABC {" a ": 12," b ": 5}Copy the code

or

Let STR = 'ABC' + encodeURIComponent(json.stringify (JSON)); //abc%.... %... A pile of codeCopy the code
Let STR = '{" a ":12," b ":5}'; let json = JSON.parse(str); / / {" a ": 12," b ": 5}Copy the code
Json is written as follows:

1. Use only double quotation marks, not single quotation marks

2. All names (keys) must be enclosed in quotes

2. The abbreviations

If the name (key) is the same as the value (value), you can write only one

Example: json = {” a “:a,” b “:b,” c “:4}; Json = {a, b, “c” :4};

Methods shorthand

Let json = {" a ":12, show:function(){alert(this.a); }}Copy the code

Abbreviated to:

Let json = {" a ":12, show(){alert(this.a); }}Copy the code

12.Promise

Asynchronous request: There is no relationship between the operations, multiple operations at the same time, complex code

Synchronous request: can only do one thing at a time, simple code

Promise clears up asynchronous operations and writes asynchronous code in the same way as synchronization

Let p1 = new Promise(function(resolve,reject){// async code // async code // async code // async code // async code // async code) Url: 'data/arr. TXT', dataType: json, success (arr) {resolve (arr); }, error(err){ reject(err); Then (function(arr){resolve() alert(" succeed "); }, function(){reject() alert(" fail "); })Copy the code

The code above is similar to using Ajax, but when you have multiple Ajax objects, create a new P2 object

Let p2 = new Promise(function(resolve,reject){$ajax({url: 'json.txt', dataType: 'json', success(arr){resolve(arr); }, error(err){ reject(err); }})}) // Use p2.then(), which is really ajax, Promise.all([p1,p2]).then.(function(arr){let [res1, res2] = arr; Alert (" It all worked "); alert(res1); alert(res2); }, function(){alert(" at least one failed "); })Copy the code

// Write p1,p2 as a function

Function createPromise(url){return new Promise(function(resolve,reject){$ajax({url:url,// Can be abbreviated as URL dataType: 'json', SUCCESS (arr){resolve(arr); },error(err){ reject(err); All ([createPromise(' data/arr.txt '), createPromise(' json.txt ')]).then.(function(arr){let [res1, res2] = arr; Alert (" It all worked "); alert(res1); alert(res2); }, function(){alert(" at least one failed "); })Copy the code

JQuery has a more convenient approach

The ajax return value in jQuery is a Promise object

Promise. All ([$. Ajax ({url: 'data/arr. TXT', dataType: "json"}), $. Ajax ({url: 'json. TXT'}, DataType: 'json')]).then.(function(results){let [arr, json] = results; Alert (" It all worked "); alert(arr); alert(json); }, function(){alert(" at least one failed "); })Copy the code

The above code can be roughly simplified to:

Promise. All ([$. Ajax ({...}), $. Ajax ({...}), $. Ajax ({...})]), then (results = > {} / / to the code, err = > {} / / when the wrong code)Copy the code

Promise.all()// Be successful, not one less

Promise.race()// Whichever is faster

Promise. Race ([$. Ajax ({url: '... ',...}), $. Ajax ({url: '... ',...})]);Copy the code

13. The generator generator

Generator is a special function. Generator functions cannot be written as arrow functions

// Ordinary functions — all the way to the end

The function show () {alert (' a '); Alert (" b "); }Copy the code

// Generator functions – Can stop in the middle and take a step, such as requesting data for asynchronous operations

// The reason for the stop-and-go is that inside the generator there are many small functions that are generated.

// For example, the following example can be split into two functions

The function show1 () {alert (' a '); {} function show2 () alert (" b "); }Copy the code

// Next (), run show1(), next(), run show2()

// The generator function is essentially this, of course this process is invisible

Function *show(){function* show() or function* show(); Show () function * alert (' a '); yield; Alert (' b '); } //show() will not execute // because the generator does not run the code inside the function directly, but instead creates a generator object let genObj = show(); alert(genObj); //[object Generator] genObj.next(); Genobj.next (); / / b pop-upCopy the code

Yield can pass parameters or return values

The ginseng

function *show(num1,num2){ alert(`${num1}`, `${num2}`); / / 99,88 alert (' a '); let a = yield; Alert (" b "); alert(a); } let genObj = show(99,88); Genobj. next(12); Genobj. next(5); // Next (5); // Parameters in next are passed to yieldCopy the code

return

The function * show () {alert (' a '); yield 12; Alert (" b "); } let gen = show(); let res1 = gen.next(); console.log(res1); //{value:12, done:false}//done :false console.log(res2); //{value:undefined, done:true}Copy the code
The function * show () {alert (' a '); yield 12; Alert (" b "); return 55; } let gen = show(); let res1 = gen.next(); console.log(res1); //{value:12, done:false}//done :false console.log(res2); //{value:55, done:true}Copy the code

Asynchronous operations

1. Generic callback functions, verbose

2. Promises are good for reading a bunch at a time

3. Generator, suitable for logical communication between content. Generator is a wrapper around Promise

4…

Another: Generator — KOA (something in Node.js)


ES7 and ES8 preview

1. Array – Includes Whether the array contains something

let arr = [32, 5, 8]; alert(arr.include(99)); //falseCopy the code

2.

Array — keys/values/entries, and for… The of cycle is used together

JSON -keys /values/entries, not yet supported

Keys – take all keys out of the array 0,1,2,3,4…

Values – remove all values from the array 12,4,5

Entries – Remove all key-value pairs in the array, a key and a value called the entry entity,{key:0,value:12},{key:1,value:4},{key:2,value:5}

for… In is used for loop arrays, loop JSON

For arrays, loop subscript key

For JSON, loop keys

for… Of is used for loop iterators

For arrays, loop values

For JSON, error: JSON is a non-iterable object, not an iterator, and has no iterator interface

Let arr =, four, five [12]; 12, let json = {" a ":" b ", 5}; for(let i in arr){ alert(i); } for(let I of arr){alert(I); // loop 12 4 5} for(let I in json){alert(I); // loop a b} for(let key in arr.keys()){alert(key); } for(let value of arr.values()){alert(value); } for(let entry of arr.entries()){alert(entry); / / cycle 2 0, 1, 4, 5} for (let (key, value) of arr. Entries ()) {alert (` ${key} = ${value} `); // loop 0=12, 1=4, 2=5Copy the code

3. The power

Math.pow(3,8)//3 to the eighth power

3 times 8 over 3 to the eighth

An array of 4.

PadStart – Patch something in front

PadEnd – to patch something back

Console. log(' (' + 'ABC'. PadStart (10) + ') '); / / (ABC) the console. The log (' (' + 'ABC'. PadStart (10, 0) + ') '); / / 0000000 (ABC) the console. The log (' (' + 'ABC'. PadEnd (10) + ') '); //(abc )Copy the code

Grammar tolerance

[12,6,8]//[12,6,8,] alert([12,6,8,])//12,6,8Copy the code

6. Parameter tolerance

function show(a,b,c,){… }// It is also true that there is a comma in the argument

7.

Use async await instead of generator yield in much the same way

Advantages of async await:

1. No dependence on external runners — unified and high performance

2. You can use arrow functions

Async function show () {alert (' a '); await; Alert (" b "); }Copy the code

// The difference between writing async await and generator yield on code implementation

// a runner is an external helper written by someone else

// use the arrow function