Digression: I haven't updated it for a long time. I learned some new things when I was learning react.js these days, and I recorded it.
1. Deconstruction and assignment
Literal meaning: one-to-one assignment should be made according to the structure of the object.
(1), ordinary variables
//ES5
let a = 1, b = 2;
//(ES6)
let [a, b] = [1,2];
The positions correspond to each other, and then you can assign values.
(2), array
let a = [1,2,3]; (ES5)
let num = a[2]; console.log( num); // 3
let [a,b,c] = [1,2,3]; (ES6)
console.log(b); //2
Nested array destructuring
let a = [1,2, [3,4],5];
let num = a[2][0]; // 3
let [a, b,[c,d],e] = [1,2, [3,4], 5] ;
console.log(b, c) // 2, 3
If the destructuring assignment is unsuccessful, the value of the variable is equal to undefined.
let [a, b] = [1];
console.log(b) // undefined
Defaults
If there is a default value, and there is no value, the default value is used;
If there is a value, take its own value, not the default value
let[a,b,c,d=4] = [1,2,3];
console.log(d);//4
let[a,b,c,d=4] = [1,2,3,5];
console.log(d);//5
Object destruction
There is an important difference between object destructuring and arrays. The elements of the array are arranged in order, and the value of the variable is determined by its position; and the properties of the object have no order, and the variable must have the same name as the property in order to get the correct value.
let obj = { name: 'xxx',age: 18};
console.log(obj.name);//'xxx'
let obj = {name:"xxx",age:"18"}
let { name: name, age: age} = obj;
console.log( name);//'xxx'
If the destructuring fails, the value of the variable is equal to undefined.
let {foo} = {bar: 'baz'};
foo // undefined
Strings can also be deconstructed and assigned. This is because at this time, the string is converted into an array-like object.
// ES5:
var res = "你好呀";
console.log(res[2]);//呀
//ES6
let[a,b,c] = "你好呀";
console.log(b);//好
Function parameter deconstruction
function show({name,age}){
//以前
// var name = obj.name;
//现在
console.log(name);//李四
console.log(name,age);//李四,18
}
let obj = {
name:"李四",
age:"18"
}
show(obj);
To be continued...
Reference materials: https://zhuanlan.zhihu.com/p/259603825
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。