ES6 new feature summary: Deconstruction assignment, template string, Symbol

1 deconstruction assignment

1.1 Spread / Rest operator

The Spread / Rest operator refers to "...", and whether it is Spread or Rest depends on the context below.

When used in iterators, it is a Spread operator. Iterator is a mechanism that traverses the elements in one or more containers in a certain order.

function foo(x, y, z) {
    console.log(x, y, z); //Three elements of output input
}
let arr = [1, 2, 3];
foo(...arr); //... Represents traversal of the arr array

The output result is: 1 2 3

When used to pass parameters to a function, it is a Rest operator.

function foo(...args) {
    console.log(args);
}
foo(1, 2, 3, 4, 5);

The output result is [1, 2, 3, 4, 5]

1.2 deconstruction of arrays

The method of assigning multiple variables in ES5 standard is:

var a = 10;
var b = 20;
var c = 30;

ES6 provides a more concise deconstruction assignment to realize the definition of the above variables:

let [a, b, c] = [10, 20, 30];
console.log(a); //Output: 10
console.log(b); //Output: 20
console.log(c); //Output: 30

The values to the right of the equal sign are assigned to the variables to the left in order.

When the left and right of the equal sign are assigned with non one-to-one correspondence, for example, when the length of the array on the left of the equal sign is less than that on the right:

let [a, b] = [1, 2, 3];
console.log(a); //Output: 1
console.log(b); //Output: 2

It can be seen that only the first two numbers 1 and 2 on the right of the equal sign are assigned to a and b. when the array length on the left of the equal sign is greater than that on the right:

let [a, b, c] = [1, 2];
console.log(a); //Output: 1
console.log(b); //Output: 2
console.log(c); //Output undefined

Then c has no assignment and the output is undefined.

You can use "..." to put specific elements in variables, for example:

let [a, ...arr] = [1, 2, 3];
console.log(a); //Output: 1
console.log(arr); //Output [2, 3]

In ES6, variables can be exchanged by deconstruction assignment, for example:

let a = 1;
let b = 2;
console.log("Before exchange:", a, b); //Output: before exchange: 1 2
[a, b] = [b, a];
console.log("After exchange:", a, b); //Output: after exchange: 2 1

1.3 deconstruction of objects

Object deconstruction is similar to array deconstruction, for example:

let obj = {
    name: "Zhang San",
    age: 20,
    height: "180cm"
}
let { name, age, height } = obj; //The name of the variable must be the same as the property name of the object
console.log(name, age, height); //Output result: Zhang San 20 180cm

You can also deconstruct multi-layer objects, such as:

let person = {
    name: "Zhang San",
    age: 20,
    family: {
        father: "Zhang Si",
        mother: "Wang Wu"
    }
}
let { name, age, family: { father, mother } } = person;
console.log(age, father); //Output: 20 sheets four

You can also customize variable names when deconstructing objects, for example:

let obj = {
    name: "Zhang San",
    age: 20
}
let { name: myname, age: myage } = obj; //Define the name myname for name and myage for age
console.log(myname, myage); //Output result: Zhang San 20

1.4 deconstruction of default values and parameters

Whether it is the deconstruction assignment of an array or the deconstruction assignment of an object, you can add default parameters. For example:

let obj = {
    name: "Zhang San",
    age: 20
}
let { name, age, height = "180cm" } = obj; //Add attribute height
console.log(name, age, height); //Output: Zhang San 20 180cm

Deconstruction is used in function parameters. Parameter deconstruction can also be given to default parameters, for example:

function fun({ name, age, height = "180cm" } = {}) { //In this function, parameters are passed into {}
    console.log(name, age, height);
}
let obj = {
    name: "Zhang San",
    age: 20
}
fun(obj); //Output: Zhang San 20 180cm

2 template string

In the ES5 standard, the general output template is through string splicing. In ES6, the splicing of strings can be simplified through template strings. The template strings are represented by back quotation marks "` ` (in the place of wavy lines on the keyboard, you can switch to English input). If you want to embed variables, it can be realized through ${variable name}, for example:

//arr is an array, and each item of the array is an object
let arr = [
    { name: "Zhang San", age: 20 },
    { name: "Li Si", age: 21 },
    { name: "Wang Wu", age: 22 }
];
let str = ""; //Define a string
for (let i = 0; i < arr.length; i++) {
    str += `full name: ${arr[i].name},Age: ${arr[i].age}. `;
}
console.log(str); //Output the splice string

The output result is: Name: Zhang San, age: 20. Name: Li Si, age: 21. Name: Wang Wu, age: 22.

3 Symbol

ES5 provides six data types: undefined, null, boolean, string, number and object.

ES6 adds a new data type: Symbol, which is used to represent unique values. Each Symbol created is unique, so that in practical application, you can create some unique attributes and define private variables.

Creation method:

let s1 = Symbol; //Create directly
let s2 = Symbol("myschool"); //Incoming string creation

At present, front-end projects are built in modularity. In order to prevent object attribute names from being overwritten, attribute names can be defined through symbol.

For example, write the following code in the a.js file:

const NAME = Symbol("name");
let obj = {
    [NAME]: "Zhang San", //[NAME] is [Symbol(name)]
    age: 20
}
export default obj; //Export object obj

Write the following code in b.js:

import obj from "./a.js"; //Import obj in a.js
const NAME = Symbol("name"); //Create another NAME
obj[NAME] = "Li Si";
console.log(obj); //Export this object

When importing other modules, you need to bring the file extension js

Note: since the node compiler does not recognize the syntax of ES6, it needs to be manually set in vscode
1. Enter the command npm init -y in the terminal to initialize the development environment of node. At this time, the terminal will automatically output the following information:

2. At this time, a file named package. XML appears in the file list JSON file, click in the file, and write "type": "module" in the next line of "main", which means that the JS file is compiled in the module management mode of ES6. At this time, b.js can run successfully.

At this time, run the b.js file, and the results are: {age: 20, [Symbol(name)]: 'Zhang San', [Symbol(name)]: 'Li Si'}

Using Symbol as the attribute name, the attribute name will not be used by object keys(),Object.getOwnPropertyNames(), for... in loop return. For example:

let obj = {
    [Symbol()]: "Zhang San",
    age: 20,
    height: "180cm"
}
let keys = Object.keys(obj); //Get all properties of obj object, excluding Symbol
console.log(keys); //Output: ['age', 'height']
console.log(Object.getOwnPropertyNames(obj)); //Output ['age ',' height ']
for (let key in obj) {
    console.log(key); //Output: age height
}

As can be seen from the above, there are three attributes in the obj object, but only two can be printed. This is also the special place of Symbol.

Object. The keys () method will return an array composed of the enumerable attributes of a given object. The order of the attribute names in the array is consistent with the order returned when the object is traversed in a normal loop.
Object. The getownpropertynames () method returns an array of property names of all its own properties of the specified object (including non enumerable properties, but excluding properties with Symbol value as name).

You can use symbols in your classes to define private properties and methods. For example:

let People = (function () {
    let name = Symbol("name"); //Define variables of Symbol type
    class People {
        constructor(yourName) {
            this[name] = yourName;
        }
        sayName() {
            console.log(this[name]);
        }
    }
    return People;
})();
let zhangsan = new People("Zhang San");
console.log(zhangsan[Symbol("name")]); //Output: undefined
zhangsan.sayName(); //Output: Zhang San

Keywords: Javascript Front-end

Added by xdentan on Wed, 15 Dec 2021 16:44:51 +0200