Home  >  Article  >  Web Front-end  >  Analysis of destructuring assignment in ES6 (code example)

Analysis of destructuring assignment in ES6 (code example)

不言
不言forward
2018-11-16 15:33:462056browse

The content of this article is about the analysis of destructuring assignment in ES6 (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

ES6 allows you to extract values ​​from arrays and objects and assign values ​​to variables according to certain patterns. This is called destructuring.

Who can destructure

Arrays can be destructured using arrays. For Set structures, array destructuring assignment can also be used.
The rule for destructuring assignment is that as long as the value on the right side of the equal sign is not an object or array, convert it to an object first.

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

In fact, as long as a certain data structure has an Iterator interface, destructuring assignment in the form of an array can be used.

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

In the above code, fibs is a Generator function (see Generator function) and has a native Iterator interface. Destructuring assignment will obtain the value from this interface in turn.
The above statements will report an error because the value on the right side of the equal sign either does not have the Iterator interface (the first five expressions) after being converted into an object, or it does not have the Iterator interface itself (the last expression).​
When the right side of the destructuring assignment expression (= the following expression) evaluates to null or undefined, an error will be thrown. Because any attempt to read null or undefined will result in a "runtime error".

Destructuring lacks initialization error

When using destructuring to declare variables with var, let or const, an initializer (that is, the value on the right side of the equal sign) must be provided. The following code will throw errors due to missing initializers:

//    语法错误!
var    {type,name};
//    语法错误!
let    {type,name};
//    语法错误!
const {type,name};

Similar to object destructuring, when using var , let , const for array destructuring, you must provide an initializer.

Declared variables are used for destructuring assignment

Object

// 错误的写法
let x;
{x} = {x: 1};
// SyntaxError: syntax error

The above code will report an error because the JavaScript engine will understand {x} as A block of code, resulting in a syntax error. This problem can only be solved by not writing the curly brace at the beginning of the line to prevent JavaScript from interpreting it as a block of code.

// 正确的写法
let x;
({x} = {x: 1});

Array

You can use array destructuring in an assignment expression, but unlike object destructuring, you don’t have to enclose the expression in parentheses, for example:

let    colors=["red","green","blue"    ],
let    firstColor    =    "black",
let    secondColor    =    "purple";
[firstColor,secondColor    ]    =    colors;
console.log(firstColor);//    "red"
console.log(secondColor);//    "green"

The value of destructuring assignment expression

The value of destructuring assignment expression is the value on the right side of the expression (after = ). This means that a destructuring assignment expression can be used anywhere a value is expected. For example, passing a value to a function:

let    node={type:    "Identifier",name:    "foo"},
let type = "Literal",
let name = 5;
function    outputInfo(value)    {
    console.log(value    ===    node);    //    true
}

outputInfo({type,name}=node);

console.log(type);//    "Identifier"
console.log(name);//    "foo"

Array destructuring assignment

Array destructuring assignment expression rvalue error

If the right side of the equal sign If it is not an array (or strictly speaking, not a traversable structure, see Iterator), an error will be reported.
If the left side is destructured using {}, the rvalue will be converted into an object, and no error will be reported except for null and undefined.

// 报错
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};

Deconstruction of one-dimensional array

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

The above code indicates that values ​​can be extracted from the array and assigned to variables according to the corresponding positions.

Destructuring of nested arrays

let    [firstColor,[secondColor]] = ["red",["green","lightgreen"],"blue"];
console.log(firstColor);//    "red"
console.log(secondColor);//    "green"

let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3

Incomplete destructuring

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

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

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

let    [,firstColor,[secondColor]] = ["red","blue",["green","lightgreen"]];
firstColor//blue
secondColor//["green","lightgreen"]

Destructuring is unsuccessful

When the item at the specified position does not exist, or its value is undefined , then the deconstruction is unsuccessful and the value of the variable is equal to undefined.

let [foo] = [];
let [bar, foo] = [1];

Default value

When the item at the specified position is not successfully deconstructed, the default value will be used.
Note that ES6 uses the strict equality operator (===) internally to determine whether a position has a value. Therefore, the default value will only take effect if an array member is strictly equal to undefined.
If an array member is null, the default value will not take effect, because null is not strictly equal to undefined.

let    colors = ["red"];
let    [firstColor,secondColor    = "green"]=colors
console.log(firstColor);//"red"
console.log(secondColor);//    "green"

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

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

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

let [x = f()] = [1];

In the above code, because x can get the value, the function f will not be executed at all. The above code is actually equivalent to the following code.
Default value can refer to other variables of destructuring assignment, 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: y is not defined

Remaining item destructuring

Array destructuring has a similar concept called rest items (rest items), which uses... syntax to assign the remaining items to a specified variable.

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

But it has another useful feature. Conveniently cloning arrays is a glaringly missed feature in JS. In ES5, developers often use a simple method, which is to use the concat() method to clone an array.

var    colors = ["red","green","blue"];
var    clonedColors = colors.concat();
console.log(clonedColors);//"[red,green,blue]"

In ES6, you can use the remaining item syntax to achieve the same effect. The implementation is as follows:

let    colors = ["red","green","blue"];
let    [...clonedColors] = colors;
console.log(clonedColors);//"[red,green,blue]"

Attention! The remaining item must be the last part of the array destructuring pattern and cannot be followed by a comma, otherwise it is a syntax error.

Destructuring assignment of objects

解构不仅可以用于数组,还可以用于对象。对象的解构与数组有一个重要的不同。数组的元素是按次序排列的,变量的取值由它的位置决定;而对象的属性没有次序,变量必须与属性同名,才能取到正确的值。  
对象的解构赋值的解构和数组的差不多,只是[]换为了{},嵌套对象多了个:,还有对象不在乎属性的顺序,所以对象的不完全解构是不必要像数组那样的,想要哪个属性直接写属性名就行了,同时还多了个别名的设置。

//普通对象的解构
let { foo, bar } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"

//嵌套对象的解构
let obj = {
  p: [
    'Hello',
    { y: 'World' }
  ]
};
let { p: [x, { y }] } = obj;
//注意,这时p是模式,不是变量,因此不会被赋值。
//如果p也要作为变量赋值,可以写成下
//let { p, p: [x, { y }] } = obj;
x // "Hello"
y // "World"
//另一个例子 
const node = {
  loc: {
    start: {
      line: 1,
      column: 5
    }
  }
};
let { loc, loc: { start }, loc: { start: { line }} } = node;
line // 1
loc  // Object {start: Object}
start // Object {line: 1, column: 5}
//注意,最后一次对line属性的解构赋值之中,只有line是变量,loc和start都是模式,不是变量。

//默认值
var {x = 3} = {};
x // 3
var {x, y = 5} = {x: 1};
x // 1
y // 5
//默认值生效的条件是,对象的属性值严格等于undefined
var {x = 3} = {x: undefined};
x // 3
var {x = 3} = {x: null};
x // null

//解构不成功,变量的值等于undefined。
let {foo} = {bar: 'baz'};
foo // undefined
// foo这时等于undefined,再取子属性就会报错
let {foo: {bar}} = {baz: 'baz'};

//由于数组本质是特殊的对象,因此可以对数组进行对象属性的解构。
let arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first // 1
last // 3
//length属性
let {length : len} = [1,2,3];
len//3

设置别名

ES6    有一个扩展语法,允许你在给本地变量赋值时使用一个不同的名称。

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'

字符串的解构赋值

字符串也可以解构赋值。这是因为此时,字符串被转换成了一个类似数组的对象。

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

类似数组的对象都有一个length属性,因此还可以对这个属性解构赋值。

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

数值和布尔值的解构赋值

解构赋值时,如果等号右边是数值和布尔值,则会先转为对象。

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

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

let {toString} = NaN;
toString === Number.prototype.toString//true

函数参数的解构赋值

函数的参数也可以使用解构赋值。

function add([x, y]){
  return x + y;
}

add([1, 2]); // 3

上面代码中,函数add的参数表面上是一个数组,但在传入参数的那一刻,数组参数就被解构成变量x和y。对于函数内部的代码来说,它们能感受到的参数就是x和y。  
函数参数的解构也可以使用默认值。

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]

上面代码中,函数move的参数是一个对象,通过对这个对象进行解构,得到变量x和y的值。如果解构失败,x和y等于默认值。当    JS    的函数接收大量可选参数时,一个常用模式是创建一个    options    对象,其中包含了附加的参数。

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]

js会先把实参传进形参的右值,代替左值,如果没传,默认用形参的右值。  
undefined就会触发函数参数的默认值。

[1, undefined, 3].map((x = 'yes') => x);
// [ 1, 'yes', 3 ]

用途

交换变量的值

let x = 1;
let y = 2;

[x, y] = [y, x];

取出从函数返回的值

函数只能返回一个值,如果要返回多个值,只能将它们放在数组或对象里返回。有了解构赋值,取出这些值就非常方便。

// 返回一个数组

function example() {
  return [1, 2, 3];
}
let [a, b, c] = example();

// 返回一个对象

function example() {
  return {
    foo: 1,
    bar: 2
  };
}
let { foo, bar } = example();

函数无次序参数的传入

解构赋值可以方便地将一组参数与变量名对应起来。

// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});

提取 JSON 数据

let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};

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

console.log(id, status, number);
// 42, "OK", [867, 5309]

函数参数的默认值

jQuery.ajax = function (url, {
  async = true,
  beforeSend = function () {},
  cache = true,
  complete = function () {},
  crossDomain = false,
  global = true,
  // ... more config
} = {}) {
  // ... do stuff
};

指定参数的默认值,就避免了在函数体内部再写var foo = config.foo || 'default foo';这样的语句。

遍历 Map 结构

任何部署了 Iterator 接口的对象,都可以用for...of循环遍历。Map 结构原生支持Iterator接口,配合变量的解构赋值,获取键名和键值就非常方便。

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

如果只想获取键名,或者只想获取键值,可以写成下面这样。

// 获取键名
for (let [key] of map) {
  // ...
}

// 获取键值
for (let [,value] of map) {
  // ...
}

输入模块的指定方法

加载模块时,往往需要指定输入哪些方法。解构赋值使得输入语句非常清晰。

const { SourceMapConsumer, SourceNode } = require("source-map");

The above is the detailed content of Analysis of destructuring assignment in ES6 (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete