ES6 --- structural assignment of variables

1, Deconstruction assignment of array

ES6 allows you to extract values from arrays and objects according to a certain pattern and assign values to variables, which is called structure. Previously, assigning values to variables can only be assigned directly;
let a =1;let b =2;let c=3;
In ES6, it can be written as:

let [a,b,c] = [1,2,3];

You can extract the value from the array and assign the value to the variable according to the corresponding position. In essence, this is the writing method of "pattern matching": as long as the patterns on both sides of the equal sign are the same, the variable on the left will be given the corresponding value;

let [foo,[ [bar],baz] ] = [1,[ [2] ,3] ];
foo//1
bar//2
baz//3

let [ , , third] = [1,2,3];
third//3

let [x, , y] = [1,2,3];
x//1
y//3

let [head ,...tail] =[1,2,3,4];
head //1
tail //[2,3,4]

let  [x,y, ...z] =["a"];
x//"a"
y//If the undefined structure fails, the value of the variable is equal to undefined
z//[]

If the pattern on the left is not completely matched, the pattern on the right can still be deconstructed;

let [x,y] = [1,2,3];
x//1
y//2

let [a,[b],d] = [1,[2,3],4];
b//2

let [a,b,c] = [1,[2,3],4];
b//[2,3]

Default value: Deconstruction assignment allows you to specify a default value.

let [foo=true] = []; //foo is true
let [x,y="b"] = ["a"];//x="a",y="b"
let [x=1] = [undefined];//x =1;
let [x=1] = [null];//x =null

ES6 internally uses the strict equality operator (= = =) to determine whether a position has a value. Therefore, if an array member is strictly not equal to undefined, the default value will not take effect

 ' '==false;//true  ' ' ===false//false
[]==false//true     []===false//false
0==false//true     0===false//false

2, Deconstruction assignment of object
Deconstruction can be used not only for arrays, but also for objects

let {name,age} = {name:"MGT360124",age:18};
name//MGT360124
age//18

The elements of the array are arranged in order, and the value of the variable is determined by its position, but the attribute of the object has no order. The variable must have the same name as the attribute in order to obtain the correct value;

let {name,age,sex} ={name:"MGT360124",age:18}
sex//undefined

let obj = {name :"MGT360124",age:18};
let {name:n,age:a} = obj
n//MGT360124
a//18 

3, Deconstruction assignment of string
The string can also be deconstructed and assigned, because the string is converted into an array like object;

let [a,b,c,d,e] = "hello";
e//o
let {length:len} = 'hello'
len//5
//Objects like arrays have a length attribute, so this attribute can also be deconstructed and assigned

4, Deconstruction assignment of numeric and Boolean values
During deconstruction assignment, if the value to the right of the equal sign is a numeric value or Boolean value, it will be turned into an object;
The object cannot be deconstructed to null as long as the object is deconstructed to null, or the object can not be deconstructed to null as long as it is not assigned an equal value.

let {toString : s } =123;
s === Number.prototype.toString //true;
let {toString : s} = true ;
s === Boolean.prototype.toString //true;
let {prop : x} = undefined;//TypeError
let {prop : y} =null;//TypeError

5, Deconstruction and assignment of function parameters

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

6, Parenthesis problem
The rule of ES is: parentheses shall not be used as long as there is ambiguity that may lead to deconstruction;
7, Purpose: the deconstruction and assignment of variables are used for many purposes
(1) Exchange values of variables

let x = 1,y =2;
[x,y] = [y,x];
x//2
y//1

(2) Returns multiple values from a function
The function can only return one value. If you want to return multiple values, you can only return them in an array or object. It is very convenient to take out these values by using deconstruction assignment

function example () {
          return [1,2,3];
}
let [a,b,c] = example();

function example() {
 return {name:"MGT360124",age:18}
}
let {name,age} =example();

(3) Definition of function parameters
Deconstruction assignment can easily correspond a set of parameters to variable names

//A parameter is an ordered set of values
function  add([x,y,x]){   }
add([1,2,3])
//A parameter is an unordered set of values
function add ( {x,y,z} ) {     }
add({y:1,z:2,x:3});

Extract json data: Deconstruction assignment is particularly useful for extracting data from json objects

let personData = {
name:"MGT360124",
age:18,
sex:"M",
city:"qinghuangdao",
job:"student",
}
let {name,age,sex,city,job} = personData;
console.log(name,age,sex,city,job);

Traverse Map structure

let map  = new Map();
map.set("first","hello");
map.set("second","world");

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

String and numeric extensions

Traversal interface of string
ES6 adds an ergodic interface to the string, so that the string can be used for Of loop traversal

for(let str of "MGT"){
console.log(str)
}
//M
//G
//T

includes() and startsWith(),endsWith()0
ES5 only has indexOf() method, which can be used to determine whether a string is included in another string. ES6 provides three methods:
includes(): returns a Boolean value indicating whether a parameter string has been found;
startsWith(): returns a Boolean value indicating whether the parameter string is at the head of the original string
endsWith(): returns a Boolean value indicating whether the parameter string is at the end of the original string

let name = "MGT360124";
name.includes("T");//true
name.startsWith("i");//true
name.endsWith("4");//true

The repeat() method returns a new string, indicating that the original string is repeated n times

'MGT360124'.repeat(3);
//"MGT360124MGT360124MGT360124"
'name'.repeat(0) ;
//' '

padStart() and padEnd()
String length completion function. If a string is not long enough, it will be completed at the head or tail. padStart() is used for head completion and padEnd() is used for tail completion
x.padStart(4,'ab'); //'abax'
x.padEnd(4,"ab");//'xaba'
padStart and padEnd accept two parameters. The first parameter is used to specify the minimum length of the string, and the second parameter is used to complete the string.
Template string
In the traditional js language, the output template is usually:

$(selector).append(
"There are <b>"+basket.count+"</b>"+"items in your basket,"+
 "<em>"+basket.onSale+"</em> are on sale!"
);

This writing method is quite cumbersome. For this reason, ES6 introduces a template string, which is an enhanced version of the string and is identified by backquotes (`). It can be used as an ordinary string, can also be used to define a multi line string, or embed variables in the string;
Then the above code can be written as follows:

$(selector).append(
 `there are <b>${basket.count}</b> items in your basket ,<em>${basket.onScale}</em> are on sale!`);

Keywords: Javascript Front-end ECMAScript

Added by caedo on Thu, 10 Mar 2022 14:06:30 +0200