ES6 Brief

What is ES6

As we all know, JavaScript from the DOM, BOM, ECMAScript composition, ECMAScript standard.
ES6 full name is actually ES2015 (6.0) updated annually, and so
ES2016 (7)
...
ES2019 (10)

Why to push ES6

One word: convenience. Can write without ES6, ES6 is to facilitate the use, use less code to do more things, in order to improve the engineering properties.

ES6 what things

variable

let used to declare a variable
const for declaring constants, and can not be modified
compared var, ES6 variable so what benefits
1. Do not re-statement
ES5

var a = 12;
var a = 5;
console.log(a)

Output is 5, that the problem is not
ES6

let a = 12;
let a = 5;
console.log(5)

image.png
It will tell you a have been defined, and can not be redefined

2. Modify control

const a = 5;
a = 12;
console.log(a);

image.png
It tells you you give constant values, this will not work

3. The support block-level scope
ES5 only function-level scope

function sum(a, b) {
  return a+b;
}
console.log(a)

image.png

This time it is on the outside of a visit less than
ES6 have block-level scope

  • {}
  • if(){}
  • for(){}
  • {}
{
  var a = 12;
}
console.log(a);

Output 12

{
  let a = 12;
}
console.log(a);

image.png

Deconstruction assignment

Without destructuring assignment

//后台读取的数据
var json = {age: 12,height: 168}
console.log(json.age,json.height);

Run deconstruction assignment

let {age,height} = {age: 12,height: 168};
console.log(age,height)

You do not need to point the
considerations
about the same on both sides of 1

let {a,b,c}={a: 12, b: 55, c: 99};//同是对象
let [a,b,c]=[12,5,8];//同是数组

2. gotta be the right thing

let {a,b,c} = {12,5,13};//右边是啥,对象?数组?都不是

image.png

function

Arrow function

Use the arrow problem not only to write a simple function and can fix this is
1. Simple
ES5

  • function xx() {}
  • function XX = var () {}
    for ES6
    the let XX = (parameter) => {}
  • Has only one parameter () can be omitted
  • And only one sentence may be omitted return {}
let show=()=>({a: 12, b: 5});//用()包一下

2. Fix the this
ES5
in ES5, who call this, this is who
in ES6, this binding in the current environment

Parameter expansion

(1) remaining parameters

function show(a, b, ...arr){
  console.log(a, b, arr);
}
show(12,5,44,7,85,34,33);

12,5,44,7,85,34,33

Note : You must be the last

function show(a, b, ...arr, c){
  console.log(a, b, arr, c);
}
show(12,5,44,7,85,34,33);

image.png
The remaining parameters have to be the last parameter

(2) expand the array
... arr equivalent to 1,5,12,3

let arr = [1,5,12,3];
var sum=(a, b, c, d)=>a+b+c+d;
console.log(sum(...arr))

21

let arr = [1, 2, 3];
let arr2 = [4, 5, 6];
let arr3 = [...arr1, ...arr2];
console.log(arr3);

1,2,3,4,5,6

System Objects

Array

4 the API, the object to call the
map mappings
forEach loop
filter filter (remove)
the reduce decrease
(1) map
mapping: 1 to 1, 100 into, out of 100

var scores = [100,60,52,48,98,13,45,66,75,98];
//两个参数item,index
var res = scores.map((item)=>item>=60);
console.log(scores,res);

image.png

(2) forEach
to sift out true

let arr = [1,5,12];
arr.forEach((item,index)=>{
  console.log(`第${index}个:${item}`);
});

Of 0: 1
of 1: 5
2nd: 12

(3)filter

let scores = [1,2,3,5,6,95,63,45,68,60];
let pass = scores.filter((item)=>item>=60);
console.log(pass)

(4) [95, 63, 68, 60]

(4) reduce
the summation

let arr = [1,5,3,16];
    let res = arr.reduce((temp,item,index)=>{
        console.log(`temp:${temp}`);
        return temp+item;
    });
    console.log(`res:${res}`);

temp: 1 // first number is the first
temp: 6 // and back are
TEMP:. 9
RES: 25

Averaging

let arr = [1,5,3,16];
    let res = arr.reduce((temp,item,index)=>{
        if(index<arr.length - 1)
            return temp+item;
        else
            return (temp+item)/2;
    });
    console.log(`res:${res}`);

String

(1) String template

let name = '小明';
console.log(`name : ${name}`);

name: Hsiao Ming

Benefits: can wrap for something very large segment of the applicable

let str = `<div>
<p>第一行${item1}</p>
<span>第二行${item2}</span>
</div>`;

(2)startsWith

let url = 'http://www.baidu.com';
if(url.startsWith('http')||url.startsWith('https')) console.log('是网址');
else console.log('不是网址')

(3)endsWith

JSON

Standard wording:

let json = {"name":"zhangsan","age":12};
  • stringify: object-json
let xiaoming = {
  name: 'xiaoming',
  age: 25
};
console.log(JSON.stringify(xiaoming));

{"name":"xiaoming","age":25}

  • parse: string transfer objects
let json = '{"name":"xiaoming","age":25}';
console.log(JSON.parse(json));

{name: "xiaoming", age: 25}

Asynchronous operation

  • Pros: good program performance, high resource utilization, a good user experience
  • Cons: programmer experience is not good

Problem : in order to pull data
environment : server
I use WampServer

data/1.json

{a: 1}

./data/2.json

{b: 12}

./data/3.json

{c: 16}

./html

 $.ajax({
      url: 'data/1.json',
      dataType: 'json',
      success(data1) {
        $.ajax({
          url: 'data/2.json',
          dataType: 'json',
          success(data2) {
            $.ajax({
               url: 'data/3.json',
            dataType: 'json',
            success(data3) {
              console.log(data1,data2,data3)
            }
          });
          }
        });
      }
    });

{a: 1} {b: 12} {c: 16}

Because such an approach nausea, so Promise appeared
look at Promise, in fact, jQuery's ajax is Promise

let p=new Promise(function (resolve, reject){//resolve成功,reject失败
      $.ajax({
        url: 'data/1.json',
        dataType: 'json',
        success(data){
          resolve(data);
        },
        error(res){
          reject(res);
        }
      });
    });

    p.then(function (data){
      alert('成功');
      console.log(data);
    }, function (res){
      alert('失败');
      console.log(res);
    });

how to use

Promise.all([
      $.ajax({url:'data/1.json', dataType: 'json'}),
      $.ajax({url:'data/2.json', dataType: 'json'}),
      $.ajax({url:'data/3.json', dataType: 'json'})
      ]).then(([data1,data2,data3])=>{
        console.log(data1,data2,data3);
    },(res)=>{
      alert('错了')//一个接口出错就不渲染
    })

{a: 1}a: 1__proto__: Object
{b: 12}b: 12__proto__: Object
{c: 16}c: 16__proto__: Object

But Promise there is a fatal flaw, not processing logic (the first data may later decide what to read)
So async / await debut, specifically with Promise, synchronous methods to asynchronous write.
But in fact, compiled or nausea nesting, but we do not need programmers to write, compile would be finished

let show = async ()=> {
  let data1 = await $.ajax({url: 'data/1.json', dataType: 'json'});//await后面跟的是Promise
  let data2 = await $.ajax({url: 'data/2.json', dataType: 'json'});
  let data3 = await $.ajax({url: 'data/3.json', dataType: 'json'});
  console.log(data1,data2,data3)
}
show();

{a: 1} {b: 12} {c: 16}

Processing logic

let show = async ()=> {
      let data1 = await $.ajax({url: 'data/1.json', dataType: 'json'});
      if(data1<10) {
        let data2 = await $.ajax({url: 'data/2.json', dataType: 'json'});
        console.log(data1,data2)
      }else {
        let data3 = await $.ajax({url: 'data/3.json', dataType: 'json'});
        console.log(data1,data3)
      }
    }
    show();

{a: 1} {c: 16}

Guess you like

Origin www.cnblogs.com/lanweipeng/p/10992884.html