This is the 26th day of my participation in the First Challenge 2022

preface

In this chapter, I will talk about the basic usage of ES6 structure assignment. Structure assignment can make our code clean and force higher. Let’s take a look.

Assignment to deconstruct

Deconstructed assignment is the way ES6 allows variables to be assigned by extracting values from arrays and objects in a pattern

Essentially, this is “pattern matching,” in which the variable on the left is assigned a corresponding value as long as the pattern on both sides of the equal sign is the same

ⅰ – Summary

  1. String deconstruction: const [a, b, c, d, e] = "hello"
  2. Numerical deconstruction: const { toString: s } = 123
  3. Boolean deconstruction: const { toString: b } = true
  4. Object to deconstruct
  • Form:const { x, y } = { x: 1, y: 2 }
  • The default:const { x, y = 2 } = { x: 1 }
  • Name:const { x, y: z } = { x: 1, y: 2 }
  1. An array of deconstruction
  • Rule: Data structures haveThe Iterator interfaceDestructuring assignments can take the form of arrays
  • Form:const [x, y] = [1, 2]
  • The default:const [x, y = 2] = [1]
  1. Function argument deconstruction
  • Array deconstruction:function Func([x = 0, y = 1]) {}
  • Object deconstruction:function Func({ x = 0, y = 1 } = {}) {}
Application scenariosCopy the code
  • Exchange variable values:[x, y] = [y, x]
  • Returns multiple values for the function:const [x, y, z] = Func()
  • Define function parameters:Func([1, 2])
  • Extract JSON data:const { name, version } = packageJson
  • Default values for defining function parameters:function Func({ x = 1, y = 2 } = {}) {}
  • Traverse the Map structure:for (let [k, v] of Map) {}
  • The input module specifies properties and methods:const { readFile, writeFile } = require("fs")

** Key and difficult points **

  • Matching pattern: As long as the pattern on both sides of the equal sign is the same, the variable on the left is assigned the corresponding value
  • Deconstruct the assignment rule: As long as the value to the right of the equals sign is not an object or array, turn it into an object first
  • The destruct default is valid only if the attribute value is strictly equal to undefined
  • Deconstruction follows a matching pattern
  • The value of the variable is equal to undefined when deconstruction fails
  • Undefined and NULL cannot be converted to objects and therefore cannot be deconstructed

ⅱ – Basic Usage

① Examples of basic usage

Previously, to assign a value to a variable, you had to specify a value directly.

let a = 1;
let b = 2;
let c = 3;
Copy the code

ES6 allows you to write it like this.

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

The above code shows that you can extract values from an array and assign values to variables in their respective locations.

Essentially, this is “pattern matching,” in which the variable on the left is assigned a corresponding value as long as the pattern on both sides of the equal sign is the same. Here are some chestnuts that are deconstructed using nested arrays.

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 : []Copy the code

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

let [foo] = [];
let [bar, foo] = [1];
Copy the code

In both cases, the deconstruction fails and the value of foo is equal to undefined.

Another case is incomplete deconstruction, where 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 : 4Copy the code

The above two chestnuts are not completely deconstructed, but can be successful.

If the right-hand side of the equals sign is not an array (or, more strictly, not a traversable structure, see the chapter On Iterator), then an error is reported.

// let [foo] = 1; let [foo] = false; let [foo] = NaN; let [foo] = undefined; let [foo] = null; let [foo] = {};Copy the code

All of the above statements will fail because the values to the right of the equals sign will either have no Iterator interface when converted to an object (the first five expressions) or will have no Iterator interface (the last expression).

For Set structures, arrays can also be destructively assigned.

let [x, y, z] = new Set(['a', 'b', 'c']);
x // "a"
Copy the code

In fact, any data structure that has an Iterator interface can be destructively assigned in the form of an array.

function* fibs() {
let a = 0;
let b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
​
let [first, second, third, fourth, fifth, sixth] = fibs();
sixth // 5
Copy the code

In the above code, FIBS is a Generator function (see Generator Functions) that natively has an Iterator interface. Deconstructing assignments in turn fetch values from this interface.

(2) the default value

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

Note that ES6 internally uses the strict equality operator (===) to determine whether a position has a value. Therefore, the default value is valid only if an array member is strictly equal to undefined.

let [x = 1] = [undefined]; //x = 1 let [x = 1] = [null]; //x = nullCopy the code

In the above code, if an array member is null, the default value does not take effect because NULL is not exactly equal to undefined.

If the default value is an expression, the expression is lazy, that is, evaluated only when it is used.

function f() { console.log('aaa'); } let [x = f()] = [1];Copy the code

In the above code, the function [f] does not execute at all because x can be evaluated. The code above is equivalent to the code below.

let x;
if ([1] === undefined) { x = f()} 
else { x = [1]; }
Copy the code

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: y is not defined
Copy the code

The last expression above fails because y has not yet been declared when x uses y as the default.

③ ES6小 点 knowledge:Continuous assignment deconstruction+ rename

This writing method is also my common writing method, very good use

let obj = {a:{b:1}} const {a} = obj; // Const {a:{b}} = obj; Const {a:{b:value}} = obj; // Continuously destruct assignment + renameCopy the code

Conclusion: this chapter is mainly about the basic usage of deconstruction assignment, I prepare a complete chapter of object deconstruction assignment in the next chapter, interested can go to understand.