2

Introduction

ES6 is a general reference, meaning that it is the next generation standard of JavaScript after version 5.1, covering ES2015, ES2016, and ES2017 grammar standards.

The new features of ES6 are currently only supported in some newer versions of browsers. To run in older versions of browsers, we need to convert ES6 to ES5.

Chrome: Starting from version 51, it can support 97% of the new ES6 features.

Firefox: Starting from version 53, it can support 97% of the new ES6 features.

Safari: Starting from version 10, it can support 99% of the new ES6 features.

IE: Edge 15 can support 96% of the new ES6 features. Edge 14 can support 93% of the new ES6 features. (IE7~11 basically do not support ES6)

Babel transcoder

It is a widely used ES6 transcoder.

npm install --save-dev @babel/core

Configuration file .babelrc

# 最新转码规则
$ npm install --save-dev @babel/preset-env

# react 转码规则
$ npm install --save-dev @babel/preset-react
// `presets`字段设定转码规则,官方提供以下的规则集,你可以根据需要安装。
  {
    "presets": [
      "@babel/env",
      "@babel/preset-react"
    ],
    "plugins": []
  }

polyfill

By default, Babel only converts the new JavaScript syntax. In order to support the new API, you need to use a polyfill to provide a shim for the current environment (that is, the previous version does not have a patch).

For example: core-js and regenerator-runtime

$ npm install --save-dev core-js regenerator-runtime
import 'core-js';
import 'regenerator-runtime/runtime';

let and const

let

In terms of scope, ES5 has only global scope and function scope. let declared with 0617292b312a12 are only valid in the code block they are in.

if(true){ let a = 1; var b = 2 }
console.log(a)// ReferenceError: a is not defined
console.log(b)// 2

Looking at the following example, we expect to output 1 , because there is only one variable i globally, so after for is executed, i=5, and the value printed by the function is always 5.

var funcs = [];
for (var i = 0; i < 5; i++) {
  funcs.push(function () {
    console.log(i);
  });
}
funcs[1](); // 5

Fix, use local storage for the i variable of each iteration, and use a closure to close the scope.

var funcs = [];
for (var i = 0; i < 5; i++) { 
    (function () {
            var local = i
            funcs.push(function () {
                console.log(local);
            });
        }
    )()
}
funcs[1](); // 1

The same effect can be achieved by let

const

const used to declare a read-only constant. Must be initialized and cannot be modified once assigned. const also have block scope.

if (true) {
 const PI = 3.141515926;
 PI = 66666 // TypeError: Assignment to constant variable.
}
console.log(PI) // ReferenceError: PI is not defined

const declare object

const obj = {};
// 为 obj 添加一个属性,可以成功
obj.name = 'hello';

// 将 obj 指向另一个对象,就会报错
obj = {}; // TypeError: "obj" is read-only

Deconstruction

Deconstruction literally means breaking down the structure, that is, breaking the original structure.

Object deconstruction

Basic usage:

let { name, age } = { name: "hello", age: 12 };
console.log(name, age) // hello 12

Set default value

let { name = 'hi', age = 12 } = { name : 'hello' };
console.log(name, age) // hello 12

The rest parameter (in the form of ...variable name) can select any number of elements from an object, and can also obtain an object composed of remaining elements.

let { name, ...remaining } = { name: "hello", age: 12, gender: '男' };
console.log(name, remaining) // hello {age: 12, gender: '男'}

Array destructuring

The rest parameter (in the form of ...variable name) selects any number of elements from the array, or you can get an array composed of the remaining elements.

let [a, ...remaining] = [1, 2, 3, 4];
console.log(a, remaining) // 1 [2, 3, 4]

Some members are ignored in array destructuring.

let [a, , ...remaining] = [1, 2, 3, 4];
console.log(a, remaining) // 1 [3, 4]

Function parameter deconstruction

Array parameter

function add([x, y]){
  return x + y;
}
add([1, 2]); // 3

Object parameters

function add({x, y} = { x: 0, y: 0 }) {
  return x + y;
}
add({x:1 ,y : 2});

Common scenarios

Without using the third variable, swap variables.

let x = 1;
let y = 2;

[x, y] = [y, x];

Extract JSON data.

let json = {
  code: 0,
  data: {name: 'hi'}
};
let { code, data: user } = json;
console.log(code, user); // 0 {name: 'hi'}

Traverse the Map structure.

const map = new Map();
map.set('name', 'hello');
map.set('age', 12);

for (let [key, value] of map) {
  console.log(key + " is " + value);
}

Expand

String expansion

Template string, this is very useful. Use backticks (`) to identify. It can be used as an ordinary string, it can also be used to define a multi-line string, or embed variables in the string.

`User ${user.name} is login...`);

Function extension

ES6 allows to set default values for the parameters of the function, that is, write directly after the parameter definition.

Once the default value of the parameter is set, when the function is declared and initialized, the parameter will form a separate scope (context). When the initialization is over, this scope will disappear. This kind of grammatical behavior will not appear when the parameter default value is not set.
function add(x, y = 1) {
    return x + y
}

Alternative to apply().

// ES5 的写法
Math.max.apply(null, [1, 3, 2])

// ES6 的写法
Math.max(...[1, 3, 2])

Array expansion

Merge array

// ES5 的写法
var list = [1,2]
list = list.concat([3])

// ES6 的写法
var list = [1,2]
list = [...list, 3]

Array new API

Array.from(), Array.of(), find() and findIndex(), etc., refer to MDN

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array

Object extension

Object properties, method abbreviations.

data = [1,2]
const resp = {data}; // 属性简写,等同于 {data: data}
const obj = {
  add(x, y) {        // 方法简写,等同于 add: function(x, y){...}
    return x + y;
  }
};

Extended attributes.

const point = {x: 1, y: 2}
const pointD = {...point, z: 3}
console.log(pointD) // {x: 1, y: 2, z: 3}

// 当有重复属性时,注意顺序问题。
const point = {x: 1, y: 2}
const pointD = {...point, x: 4, z: 3}
console.log(pointD) // {x: 4, y: 2, z: 3}

const point = {x: 1, y: 2}
const pointD = {x: 4, z: 3, ...point}
console.log(pointD) // {x: 1, z: 3, y: 2}

Attribute description object

Each property of the object has a description object (Descriptor), which is used to control the behavior of the property.

const point = {x: 1, y: 2}
Object.getOwnPropertyDescriptor(point, 'x') 
/**
{    configurable: true
     enumerable: true // 表示可枚举
    value: 1
    writable: true   // 表示可写
 }
**/

Attribute traversal

  • for...in loop: only traverse the object's own and inherited enumerable properties.
  • Object.keys() : Returns the key names of all enumerable properties of the object itself.
  • JSON.stringify() : Only serialize the enumerable properties of the object itself.
  • Object.assign() : Ignore enumerable as false , and only copy the enumerable attributes of the object itself.
const point = {x: 1, y: 2}
for(let key in point){
  console.log(key)
}

Some new methods of objects: Object.assign()

Object.assign() method implements a shallow copy, not a deep copy. In other words, if the value of an attribute of the source object is an object, then the target object is copied as a reference to this object. Common uses:

Clone object

function clone(origin) {
  return Object.assign({}, origin);
}

Merge object

const merge = (target, ...sources) => Object.assign(target, ...sources);

Specify default value

const DEFAULT_CONFIG = {
  debug: true,
};

function process(options) {
  options = Object.assign({}, DEFAULT_CONFIG, options);
  console.log(options);
  // ...
}
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object

Operator expansion

Exponent operator

2 ** 10 // 1024
2 ** 3 ** 2 // 512 相当于 2 ** (3 ** 2)

let a=10; a **= 3; // 相当于 a = a * a * a

Chain judgment operator

obj?.prop determines whether the object attribute exists, and whether the func?.(...args) function or object method exists.

const obj = {name: 'job', say(){console.log('hello')}}
obj?.name  // 等于 obj == null ? undefined : obj.name
obj?.say() // 等于 obj == null ? undefined : obj.say()

Null judgment operator

In JavaScript, we use the || operator to specify the default value. When we want the default value to be triggered when the left side is null and undefined, use ?? .

const obj = {name: ''}
obj.name || 'hello' // 'hello'
obj.name ?? 'hello' // ''

for...of

Because the for...in loop is mainly designed for traversing objects, because the key name of the array is a number, it returns a number when traversing the array. Obviously, this cannot meet the development needs. Using for...of can solve this problem.

const list = ['a', 'b', 'c']
for (let v in list){
  console.log(v) // 0,1,2
}
for (let v of list){
  console.log(v) // a,b,c
}

summary

To review the main points of this article, please leave a message for exchange.

  • ES6 introduction.
  • let and const variables.
  • Deconstruct the object array.
  • Some new extensions.

编程码农
452 声望1.4k 粉丝

多年编程老菜鸟👨‍💻🦍