Deconstruction and assignment of variables in ES6

Destructuring assignment

1. Deconstruction and assignment of array

Basic Usage

  • The left and right sides have the same structure
  • Right must be a legal value
  • Declaration and assignment cannot be separated in one sentence
let arr = [1, 2, 3];

let a =  arr[0];
let b = arr[1];
let c = arr[2];

console.log(a, b, c);

After deconstruction assignment:

let [a, b, c]=[1, 2, 3];
console.log(a, b, c);

let [{a, b}, [{n1, n2, n3}], num, str] = [{1,2}, [{3, 4, 5}], 6, "str"];

let {a, b} = {1, 2}; this writing is unreasonable, and the right side is not a legal value

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'
  • The strict equality operator (====) is used in ES6 to determine whether a position has a value. Therefore, when an array member is strictly equal to undefined, the default value will take effect
let [x = 1] = [undefined];
x // 1

let [x = 1] = [null];
x // null

For example:

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

2. Deconstruction and assignment of objects

Use

  1. There is an important difference between the deconstruction of an object and that of an array. The elements of an array are arranged in order, and the value of a variable is determined by its position. However, there is no order for the attributes of an object. A variable must have the same name as an attribute in order to get the correct value
let  {a, b} = {a: "aaa", b: "bbb"};
a //"aaa"
b //"bbb"

let { c } = {a: "aaa", b: "bbb"};
c //undefined
  1. If the variable name does not match the property name
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'

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

In the above code, foo is the matching pattern and baz is the variable. It is the variable baz, not the pattern foo, that is really assigned.
3. Deconstruct objects for nested structure

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

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

At this time, p is a pattern, not a variable, so it will not be assigned. If p wants to assign an Orwellian variable, it should be written as follows:

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

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

Default value

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

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

The default value is valid if the property value of the object is exactly equal to undefined.

Attention points

  1. JS will understand {x} as a code block, which can be solved only when the braces are not written at the beginning of the line
//Wrong writing
let x;
{x} = {x: 1};

//Correct writing
({x} = {x:1}});
  1. The deconstruction assignment allows no variable name to be placed in the pattern to the left of the equal sign. But expressions don't make sense
({} = [true, false]);
  1. 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

3. Deconstruction and assignment of strings

  1. Strings can also be deconstructed and assigned. Strings are converted into an array like object
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"  
d // "l"
e // "o"
  1. Objects like arrays have the length attribute
let {length : len} = "hello";
len //5

4. Deconstruction and assignment of values and Booleans

  1. Wrapper objects for numeric and Boolean values have toString properties
let {toString : s} = 123;
s === Number.prototype.toString // true

let {toString: s} = true;
s === Boolean.prototype.toString // true
  1. undefined and null cannot be converted to objects, so when they are deconstructed, an error TypeError will be reported
let { prop :x } = undefined;  //TypeError
let { prop : y } = null; //TypeError

5. Deconstruction and assignment of function parameters

  1. An example of deconstruction and assignment of function parameters is given:
[[1, 2], [3, 4]].map(([a, b]) => a + b);
// [ 3, 7 ]
  1. The default value of the deconstruction of the function parameter data. The parameter of the function is the object. Through the deconstruction of the object, the x and y values are obtained. The deconstruction failure is equal to the x and y 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]
  1. Specifying default values for function parameters has different effects
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]

6. Parentheses

Situations where parentheses cannot be used

  1. Variable declaration statement
//All reported errors
let [(a)] = [1];

let {x: (c)} = {};
let ({x: c}) = {};
let {(x: c)} = {};
let {(x): c} = {};

let { o: ({ p: p }) } = { o: { p: 2 } };
  1. Function parameter
//Report errors
function f( [(a)] ){ return a; }
  1. Mode of assignment statement
//Report errors
({ p : a}) = { p : 42 };

Situations where parentheses can be used

  • For the non modal part of the assignment statement, note the following conditions:
  1. It's an assignment statement, not a declaration statement
  2. Parentheses are not part of the pattern
[(b)] = [3]; // Correct
({ p: (d) } = {}); // Correct
[(parseInt.prop)] = [3]; // Correct

In the second example, p is the pattern, and d is the variable

7. Use of deconstruction assignment

  • Value of exchange variable
let x =1;
let y = 2;
[ x, y ] = [ y, x ];
  • Return multiple values from function
    • The function can only return one value, and can only return it to an array or an object. It is easy to use deconstruction to assign values.
// Return array
 function example (){
 	return [1, 2, 3];
 }
 let [a, b, c]=example();

//Return object
 function example(){
 	return {
 		foo: 1,
 		bar: 2
	 }
 }
 let { foo, bar }  = example();
  • Definition of function parameters
    • Convenient one-to-one correspondence between parameter and variable name
//Parameters are ordered
function f([x, y, z]){...}
f([1, 2, 3]);

//Parameters are unordered
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});
  • Extract JSON data
let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};

let { id, status, data: number } = jsonData;

console.log(id, status, number);
// 42, "OK", [867, 5309]
  • Default value of function parameter
jQuery.ajax = function (url, {
  async = true,
  beforeSend = function () {},
  cache = true,
  complete = function () {},
  crossDomain = false,
  global = true,
  // ... more config
} = {}) {
  // ... do stuff
};
  • Traversal Map structure
const 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

// Get key name
for (let [key] of map) {
  // ...
}

// Get key value
for (let [,value] of map) {
  // ...
}
  • Input module specifying method
    • On demand import component of vue Mint UI
import { Header, Swipe, SwipeItem, Button, Lazyload } from 'mint-ui'
Published 14 original articles, won praise 0, visited 209
Private letter follow

Keywords: Attribute JSON JQuery Vue

Added by blkraven on Sun, 01 Mar 2020 16:12:36 +0200