ECMAScript 6 common knowledge and examples of finishing, include (ECMAScript 7/8/9)

Tip: article length is longer, involving more knowledge, it is recommended to watch after collection.

table of Contents

and let const

Deconstruction assignment

Use the arrow function

Template string

Default function arguments

Operators Expand

Object literal with class

Promise

An array of new methods

Object new method

Infix exponentially


and let const

let const and features:

  1. Not be promoted
  2. Repeat statement error
  3. Does not bind global scope (block-level scope)

Temporary dead zone: variable (TDZ) let const statement and will not be raised to the top of the scope, if access these variables before declaration will lead to error:

var value = "global";
// 例子1
(function() {
    console.log(value);
    let value = 'local';
}());

// 例子2
{
    console.log(value);
    const value = 'local';
};
// 两个例子中,结果并不会打印 "global",而是报错 Uncaught ReferenceError: value is not defined,就是因为 TDZ 的缘故。

Deconstruction assignment

Destructuring assignment expression syntax is a Javascript, which makes it possible to extract the data objects to or from an array of different variables

const person = {
  name: 'little bear',
  age: 18,
  sex: '男'
}
let { name,age,sex } = person
//数组
let nbaStars=['yaoming','kobe','james','paul']
let [chinaStar,...usaStar] = nbaStars
let [,,,myidol] = nbaStars
console.log(usaStar,chinaStar,myidol)
//["kobe", "james", "paul"] "yaoming" "paul"

Use the arrow function

// es5
var fn = function(a, b) {
    return a + b;
}
// es6 箭头函数写法,当函数直接被return时,可以省略函数体的括号
const fn = (a, b) => a + b;

// es5
var foo = function() {
    var a = 20;
    var b = 30;
    return a + b;
}
// es6
const foo = () => {
   const a = 20;
   const b = 30;
   return a + b;
}

# Use the arrow function to note the following:

  • Arrow function can replace the function expression, but can not replace the function declaration;
  • Arrow function, not this. If you use this function in the arrow, then this certainly is the outer layer of this;
  • In ES6, the strict default mode, so this will not automatically point to the window object;
  • Arrow function itself and not this;
  • Arrow function can not access the arguments object.

Template string

Use `wrapped up the entire character string, and wherein the package $ {} to a variable or an expression.

// es6
const a = 20;
const b = 30;
const string = `${a}+${b}=${a+b}`;

// es5
var a = 20;
var b = 30;
var string = a + "+" + b + "=" + (a + b);

Default function arguments

function add(x = 20, y = 30) {
    return x + y;
}
console.log(add());

Operators Expand

In ES6 represented by ... expand operator, or it may be an array of object methods to expand.

数组展开:
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 10, 20, 30];
// 这样,arr2 就变成了[1, 2, 3, 10, 20, 30];

对象展开:
const obj1 = {
  a: 1,
  b: 2,
  c: 3
}
const obj2 = {
  ...obj1,
  d: 4,
  e: 5,
  f: 6
}

// 结果类似于 const obj2 = Object.assign({}, obj1, {d: 4})

Object literal with class

  1. When the value of the variable with the same name attribute
    const name = 'Jane';
    const age = 20
    
    // es6
    const person = {
      name,
      age
    }
    
    // es5
    var person = {
      name: name,
      age: age
    };

     

  2. In addition to the properties, the method object literal wording may also abbreviated manner.
    // es6
    const person = {
      name,
      age,
      getName() { // 只要不使用箭头函数,this就还是我们熟悉的this
        return this.name
      }
    }
    
    // es5
    var person = {
      name: name,
      age: age,
      getName: function getName() {
        return this.name;
      }
    };

     

  3. You can use brackets in the object literal as a property, which is also the name of a property variables.
    const name = 'Jane';
    const age = 20
    
    const person = {
      [name]: true,
      [age]: true
    }

     

  4. ES6 provides a new syntactic sugar we create objects, which is Class syntax.
    // ES5
    // 构造函数
    function Person(name, age) {
      this.name = name;
      this.age = age;
    }
    
    // 原型方法
    Person.prototype.getName = function() {
      return this.name
    }
    
    // ES6
    class Person {
      constructor(name, age) {  // 构造函数
        this.name = name;
        this.age = age;
      }
    
      getName() {  // 原型方法
        return this.name
      }
    }
    babel会将ES6的写法编译成为利用Object.defineProperty实现的方式,包括get,set等。
    

     

  5. In addition, we also need to pay special attention to the wording in several different ways in actual use, the comments in the following example, I explain the meaning they were in the corresponding ES5.
    class Person {
      constructor(name, age) {  // 构造函数
        this.name = name;
        this.age = age;
      }
    
      getName() {   // 这种写法表示将方法添加到原型中
        return this.name
      }
    
      static a = 20;  // 等同于 Person.a = 20
    
      c = 20;   // 表示在构造函数中添加属性 在构造函数中等同于 this.c = 20
    
    // 箭头函数的写法表示在构造函数中添加方法,在构造函数中等同于this.getAge = function() {}
      getAge = () => this.age   
    }
    
    继承 extends
    相比ES5,ES6的继承就要简单很多:
    class Person {
      constructor(name, age) {
        this.name = name;
        this.age = age;
      }
    
      getName() {
        return this.name
      }
    }
    
    // Student类继承Person类
    class Student extends Person {
      constructor(name, age, gender, classes) {
        super(name, age);
        this.gender = gender;
        this.classes = classes;
      }
    
      getGender() {
        return this.gender;
      }
    }

     

  6. We only need one extends keyword, you can achieve inherited, not to worry as the constructor inheritance and prototype inheritance like ES5, in addition, we also need to focus on a method called the super.
    /* 在继承的构造函数中,我们必须如上面的例子那么调用一次super方法,
        它表示构造函数的继承,与ES5中利用call/apply继承构造函数是一样的功能。 */
    // 构造函数中
    // es6
    super(name, age);
    
    // es5
    Person.call(this);

     

Promise

In the native realize ajax, the use of the onreadystatechange event, when the event triggers and meet certain conditions in order to get the data we want, then we can begin processing the data. Doing so does not seem any trouble, but if this time, we need to do another ajax request, this new ajax request of one of the parameters, have to get from a ajax request, this time we had the following manner do:

var url = 'https://hq.tigerbrokers.com/fundamental/finance_calendar/getType/2017-02-26/2017-06-10';
var result;

var XHR = new XMLHttpRequest();
XHR.open('GET', url, true);
XHR.send();

XHR.onreadystatechange = function() {
    if (XHR.readyState == 4 && XHR.status == 200) {
        result = XHR.response;
        console.log(result);

        // 伪代码
        var url2 = 'http:xxx.yyy.com/zzz?ddd=' + result.someParams;
        var XHR2 = new XMLHttpRequest();
        XHR2.open('GET', url, true);
        XHR2.send();
        XHR2.onreadystatechange = function() {
            ...
        }
    }
}

When there is a third ajax (or even more) is still dependent on a request, our code becomes a disaster. The disaster, often referred to as the callback hell.

So we need a thing called Promise, and to solve this problem.

Of course, in addition to the callback hell, there is a very important requirement: To our code more readable and maintainable, we need to deal with data requests and data clearly distinguished.

Promise object has three states, they are:

  • pending: waiting, or for, the result obtained indicates that no
  • resolved (Fulfilled): has been completed, said they have the results we want, we can continue down
  • rejected: also said to get results, but as a result is not what we wish, therefore refuse to perform
new Promise(function(resolve, reject) {
    if(true) { resolve() };
    if(false) { reject() };
})

Promise.all:

Promise.all receiving a Promise array of objects as a parameter, when all this array of state Promise objects have become resolved or when rejected, and it will then go to call method.

var url = '...';
var url1 = '...';

function renderAll() {
    return Promise.all([getJSON(url), getJSON(url1)]);
}
renderAll().then(function(value) {
    console.log(value);
})

Promise.race:

And Promise.all Similarly, Promise.race Promise is an array of objects as a parameter, the difference is that whenever a state wherein a Promsie array becomes resolved or rejected, the method can invoke the .then .

function renderRace() {
    return Promise.race([getJSON(url), getJSON(url1)]);
}

renderRace().then(function(value) {
    console.log(value);
})

An array of new methods

1. Array.prototype.includes

    It includes a function of a Array useful for quickly find the array contains an element. (Including NaN, and so indexOf is not the same).

2. Jifukushi added

    Provides two additional methods String.prototype.padStart strings and String.prototype.padEnd, we will facilitate a new string appended to the beginning and end of a string.

'someString'.padStart(numberOfCharcters [,stringForPadding]);
'5'.padStart(10) // '          5'
'5'.padStart(10, '=*') //'=*=*=*=*=5'
'5'.padEnd(10) // '5         '
'5'.padEnd(10, '=*') //'5=*=*=*=*='

Object.entries(cars).map(([name, count]) => {
    console.log(`${name.padEnd(20, '-')} Count:${count.toString().padStart(3, '0')}`)
})
/*
?ambulance--------- Count:003
?car--------------- Count:007
?trucks------------ Count:004
*/

3. Array.prototype.flat()  ( ES9 )

    Array.prototype.flat () recursively nested array split to a specified depth. The default value is 1, if you want to use the full depth of Infinity. This method does not modify the original array, but creates a new array:

const arr1 = [1, 2, [3, 4]];
arr1.flat();  // [1, 2, 3, 4]
const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat(2);  // [1, 2, 3, 4, 5, 6]
 
const arr3 = [1, 2, [3, 4, [5, 6, [7, 8]]]];
arr3.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8]
flat() 方法会移除数组中的空项:
const arr4 = [1, 2, , 4, 5];
arr4.flat(); // [1, 2, 4, 5]

4. Array.prototype.flatMap()  (ES9)

    flatMap () method first mapping function maps each element, then the result is compressed into a new array. It is almost the same depth and Array.prototype.map Array.prototype.flat 1, but flatMap usually combined into a slightly higher efficiency of the process.

const arr1 = [1, 2, 3];
 
arr1.map(x => [x * 4]); // [[4], [8], [12]]
 
arr1.flatMap(x => [x * 4]); // [4, 8, 12]

Better example:

const sentence = ["This is a", "regular", "sentence"];
 
sentence.map(x => x.split(" ")); 
// [["This","is","a"],["regular"],["sentence"]]
 
sentence.map(item => item.split(' ')).flat(Infinity)
// ["This","is","a","regular", "sentence"]

sentence.flatMap(x => x.split(" ")); 
// ["This","is","a","regular", "sentence"]
 
// 可以使用 归纳(reduce) 与 合并(concat)实现相同的功能
sentence.reduce((acc, x) => acc.concat(x.split(" ")), []);

Object new method

1.Object.values()

   Object.values ​​() function and Object.keys () is very similar, it returns an object of all values ​​in their own property (inherited through the prototype chain is not).

2. Object.entries()

    Object.entries () and related Object.keys, but entries () function will be key and value as an array of return. Thus, the use of recycled or will be converted to Map objects very convenient.

let obj = { 'dsds': 2, 'fsdsg': 3, 'gththt': 4 }
console.log(Object.entries(obj))
/* 
(3) [Array(2), Array(2), Array(2)]
0: (2) ["dsds", 2]
1: (2) ["fsdsg", 3]
2: (2) ["gththt", 4]
*/

3.Object.fromEntries (ES9)

The list of key-value pairs into a new method Object.

It is contrary to prior Object.entries (), Object.entries () method is used when converting an array object, it returns the object itself a given key-value be enumerated attribute array.

But now you can return to the object by an array Object.fromEntries the operation.

const obj = { prop1: 2, prop2: 10, prop3: 15 };
 
// 转化为键值对数组:
let array = Object.entries(obj); 
// [["prop1", 2], ["prop2", 10], ["prop3", 15]]
// 将所有对象属性的值平方:
array = array.map(([key, value]) => [key, value ** 2]); 
// [["prop1", 4], ["prop2", 100], ["prop3", 225]]

We converted the array array as a parameter Object.fromEntries, will be converted into an object array:

const newObj = Object.fromEntries(array); 
// {prop1: 4, prop2: 100, prop3: 225}

It refers to the conjugate of logarithmically

Add / subtract with which we are usually decorated in the form of intuitive and easy to understand. In ECMAScript2016, we can use * instead Math.pow.

 

If you see here and feel there is so little help to you, please praise or encourage my comments.

Published 94 original articles · won praise 29 · views 50000 +

Guess you like

Origin blog.csdn.net/weixin_41849462/article/details/101692999