Ab initio front end --es6 (deconstruction and assignment of array)

Posted by playa4real on Fri, 21 Jan 2022 05:59:35 +0100

Deconstruction assignment of array

Basic Usage

ES6 allows you to extract values from arrays and objects and assign values to variables according to a certain pattern, which is called deconstructing.

es5 declares multiple variables at once

var a = 1,
    b = 2,
    c = 3,
    ...;

es6 declares multiple variables at once

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

In essence, this writing belongs to "pattern matching". As long as the patterns on both sides of the equal sign are the same, the variables on the left will be given corresponding values.

let [foo, [[bar], baz]] = [1, [[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 // [2, 3, 4]

let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []

If the deconstruction is unsuccessful, the value of the variable is equal to undefined.

let [foo] = [];
let [bar, foo] = [1];
//foo is undefined

Another case is incomplete deconstruction, that is, the pattern to the left of the equal sign matches only part of the array to the right of the equal 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

//The above two examples belong to incomplete deconstruction, but they can be successful.

If the right side of the equal sign is not an array, an error will be reported.

// report errors
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};

Default value

Deconstruction assignment allows default values to be specified.

let [foo = true] = [];
foo // true

let [x, y = 'b'] = ['a']; // x='a', y='b'
let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'

Note that ES6 uses the strict equality operator (= = =) internally to judge whether a position has a value. Therefore, 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

If the default value is an expression, the expression is evaluated lazily, that is, it will be evaluated only when it is used.

function f() {
  console.log('aaa');
}

let [x = f()] = [1];
//Equivalent to
let x;
if ([1][0] === undefined) {
  x = f();
} else {
  x = [1][0];
}

The default value can refer to other variables assigned by deconstruction, but the variable must have been 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 reason why the last expression above reports an error is that when x uses the default value y, y has not been declared

Deconstruction assignment of object

Deconstruction can be used not only for arrays, but also for objects.

let { foo, bar } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"

There is an important difference between the deconstruction of objects and arrays. The elements of the array are arranged in order, and the value of the variable is determined by its position; The attributes of the object have no order, and the variable must have the same name as the attribute in order to get the correct value.

let { bar, foo } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"

let { baz } = { foo: "aaa", bar: "bbb" };
baz // undefined

If the variable name is inconsistent with the property 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'

In fact, the deconstruction assignment of an object is the abbreviation of the following form

let { foo: foo, bar: bar } = { foo: "aaa", bar: "bbb" };

In other words, the internal mechanism of object deconstruction assignment is to find the attribute with the same name first, and then assign it to the corresponding variable. What is really assigned is the latter, not the former.

let { foo: baz } = { foo: "aaa", bar: "bbb" };
baz // "aaa"
foo // error: foo is not defined

Like arrays, deconstruction can also be used for nested objects.

let obj = {
  p: [
    'Hello',
    { y: 'World' }
  ]
};

let { p: [x, { y }] } = obj;
x // "Hello"
y // "World"

Object deconstruction 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"

The default value takes effect if the property value of the object is strictly equal to undefined.

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

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

If the deconstruction mode is a nested object and the parent attribute of the child object does not exist, an error will be reported.

// report errors
let {foo: {bar}} = {baz: 'baz'};
//The foo attribute of the object to the left of the equal sign corresponds to a child object. The bar attribute of this sub object will report an error during deconstruction. The reason is very simple, because foo is equal to undefined, and an error will be reported if you take the sub attribute,

Because arrays are special objects in nature, they can be deconstructed.

let arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first // 1
last // 3

Deconstruction assignment of string

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

Objects like arrays have a length attribute, so you can also deconstruct and assign values to this attribute.

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

Deconstruction assignment of function parameters

function add([a,b]){
  return a+b;
}
add([2,3])//5

Deconstruction of function parameters can also use 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]

Note that the following writing will get different results.

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]
//

The above code specifies the default value for the parameters of the function move, rather than the default value for variables x and y, so it will get a different result from the previous writing method.

purpose

  1. In addition, you can define multiple variables at once
  2. You can also have functions return multiple values
  3. You can easily make the parameters of the function correspond to the values
  4. Extract json data
  5. Default values for function parameters

Topics: Javascript Front-end ECMAScript