Array destruct assignment

  1. Es5 declares multiple variables at once.
var a = 1,
    b = 2,
    c = 3;
Copy the code
  1. Es6 declares multiple variables at once.
let [a, b, c] = [1.2.3]; //a=1,b=2,c=3
Copy the code
  1. Es6 is “pattern matching”. As long as the pattern on both sides of the equal sign is the same, the variable on the left side will be assigned the corresponding value.
let [foo, [[bar], baz]] = [1The [[2].3]].//foo=1,bar=2,baz=3

let [ , , third] = ["foo"."bar"."baz"]; //third="baz"

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

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

let [x, y, ...z] = ['a']; //x="a",y=undefined,z=[]
Copy the code
  1. If the deconstruction fails, the value of the variable is equal to undefined.
let [foo] = [];
let [bar, foo] = [1];
/ / foo is undefined
Copy the code
  1. Incomplete deconstruction, in which the pattern to the left of the equals sign matches only part of the array to the right of the equals sign. In this case, deconstruction can still succeed.
let [x, y] = [1.2.3]; //x=1,y=2

let [a, [b], d] = [1[2.3].4]; //a=1,b=2,d=4
Copy the code
  1. If the right-hand side of the equals sign is not an array, then an error is reported.
/ / an error
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};
Copy the code
  1. Destruct assignment allows you to specify default values.
let [foo = true] = []; //foo=true
let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a'.undefined]; // x='a', y='b'
Copy the code
  1. Es6 internally uses the strict equality operator (===) to determine whether a position has a value, so if an array member is not strictly equal to undefined, the default value will not take effect.
let [x = 1] = [undefined]; //x=1

let [x = 1] = [null]; //x=null
Copy the code
  1. If the default value is an expression, the expression is lazy, that is, evaluated only when it is used.
function f() {
    console.log('aaa'); // Will not be executed
}
let [x = f()] = [1];

/ / equivalent to the
let x;
if ([1] [0= = =undefined) {
    x = f();
} else {
    x = [1] [0];
}
Copy the code
  1. The default value can refer to another variable of the deconstructed assignment, but that variable must already be declared.
let [x = 1, y = x] = [];     // x=1; y=1
let [x = 1, y = x] = [2];    // x=2; y=2
let [x = 1, y = x] = [1.2]; // x=1; y=2
let [x = y, y = 1] = [];     // ReferenceError
// The last expression above fails because y has not been declared when x uses the default value
Copy the code

2. Object deconstruction assignment

  1. Deconstruction can be applied to objects as well as arrays. An important difference between object deconstruction and array is that the elements of an array are arranged in order, and the value of a variable is determined by its position, whereas the attributes of an object have no order, and the variables must have the same name as the attributes to get the correct value.
let { bar, foo } = { foo: "aaa".bar: "bbb" }; / / foo = "aaa", the bar = "BBB"
let { baz } = { foo: "aaa".bar: "bbb" }; // baz=undefined
Copy the code
  1. If the variable name does not match the attribute name, it must be written as follows.
let { foo: baz } = { foo: 'aaa'.bar: 'bbb' }; // baz="aaa"

let obj = { first: 'hello'.last: 'world' };
let { first: f, last: l } = obj; //f='hello' l= 'world'
Copy the code
  1. In fact, deconstructive assignment of an object is shorthand for the following. The internal mechanism for deconstructing assignment of an object is to find the property of the same name and then assign it to the corresponding variable. It is the latter, not the former, that is really assigned.
let { foo: foo, bar: bar } = { foo: "aaa".bar: "bbb" };

let { foo: baz } = { foo: "aaa".bar: "bbb" }; //baz="aaa", foo is not defined
Copy the code
  1. Like arrays, object deconstruction can also be used for nested structured objects.
let obj = {
    p: [
        'Hello',
        { y: 'World'}};let { p: [x, { y }] } = obj;
x // "Hello"
y // "World"
Copy the code
  1. The deconstruction of an object can also specify default values.
var {x = 3} = {};
x / / 3

var {x, y = 5} = {x: 1};
x / / 1
y / / 5

var {x: y = 3} = {};
y / / 3

var {x: y = 3} = {x: 5};
y / / 5

var { message: msg = 'Something went wrong' } = {};
msg // "Something went wrong"
Copy the code
  1. The default takes effect only if the value of an object’s property is strictly equal to undefined.
var {x = 3} = {x: undefined};
x / / 3

var {x = 3} = {x: null};
x // null
Copy the code
  1. An error is reported if the deconstruction pattern is a nested object and the parent property of the child object does not exist.
/ / an error
let {foo: {bar}} = {baz: 'baz'};
// The attribute foo of the object to the left of the equals sign corresponds to a child object. The bar property of this child object will report an error when deconstructed. The reason for this is simple, because foo is equal to undefined, and taking the child property is an error
Copy the code
  1. Since arrays are special objects in nature, they can be deconstructed as object properties.
let arr = [1.2.3];
let {0 : first, [arr.length - 1] : last} = arr;
first / / 1
last / / 3
Copy the code

String deconstruction assignment

const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
Copy the code

Array-like objects have a length attribute, so you can also deconstruct and assign to this attribute.

let {length : len} = 'hello';
len / / 5
Copy the code

4. Deconstruction and assignment of function parameters

function add([a,b]){
  return a+b;
}
add([2.3])/ / 5
Copy the code

Function arguments can also be destructed using default values.

function move({x = 0, y = 0} = {}) {
  return [x, y];
}

move({x: 3.y: 8}); / / [3, 8]
move({x: 3}); / / [3, 0]
move({}); / / [0, 0]
move(); / / [0, 0]
Copy the code
// The following code specifies default values for the arguments to the function 'move', instead of for the variables' x 'and' y ', so the result is different from the previous one.
function move({x, y} = { x: 0, y: 0 }) {
  return [x, y];
}

move({x: 3.y: 8}); / / [3, 8]
move({x: 3}); // [3, undefined]
move({}); // [undefined, undefined]
move(); / / [0, 0]
Copy the code

5. Deconstructive assignment of values and Boolean values

When deconstructing an assignment, if the value and Boolean are to the right of the equals sign, the object is converted first.

let {toString: s} = 123;
s === Number.prototype.toString // true

let {toString: s} = true;
s === Boolean.prototype.toString // true
Copy the code

6. Parentheses

  1. While deconstructing assignments is convenient, it’s not easy to parse. There is no way for the compiler to know from the start whether an expression is a pattern or an expression. It must be parsed to (or not) the equals sign.
  2. Parentheses should not be used in ES6 where there is ambiguity that could lead to deconstruction. Whenever possible, do not place parentheses in patterns.
  3. Destructible assignments that cannot use parentheses include variable declarations, that is, () cannot occur when there islet,constDeclaration statement.
// All errors are reported
let [(a)] = [1];
let {x: (c)} = {};
let ({x: c}) = {};
let {(x: c)} = {};
let {(x): c} = {};
let { o: ({ p: p }) } = { o: { p: 2}};Copy the code
  1. Function arguments are also variable declarations and therefore cannot have parentheses.
/ / an error
function f([(z)]) { return z; }
/ / an error
function f([z,(x)]) { return x; }
Copy the code
  1. The () cannot appear in the assignment statement pattern.
// All errors are reported
({ p: a }) = { p: 42 };
([a]) = [5];
// The above code puts the entire schema in parentheses, causing an error.
/ / an error
[({ p: a }), { x: c }] = [{}, {}];
Copy the code
  1. There is only one case in which parentheses can be used, and that is for the non-schema part of an assignment statement.
[(b)] = [3]; / / right
({ p: (d) } = {}); / / right
[(parseInt.prop)] = [3]; / / right
Copy the code

All three of the above lines execute correctly because they are assignment statements, not declarations; Second, their parentheses are not part of the schema. In the first line, the schema takes the first member of the array, regardless of parentheses; In the second line, the mode is P, not D; The third line of statements has the same properties as the first.

Deconstruct the purpose of assignment

  1. Multiple variables can be defined at once.
  2. You can make a function return multiple values.
  3. You can easily match the parameters of a function to the values.
  4. Json data can be extracted.
  5. You can provide default values for function arguments.