解构赋值

本文共--字 阅读约--分钟 | 浏览: -- Last Updated: 2022-06-17

数组的解构赋值

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

如果等号的右边不是数组(或者严格地说,不是可遍历的结构),那么将会报错。

对象的解构赋值

对象的解构与数组有一个重要的不同。数组的元素是按次序排列的,变量的取值由它的位置决定;而对象的属性没有次序,变量必须与属性同名,才能取到正确的值。

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

// foo是匹配的模式,baz才是变量。真正被赋值的是变量baz,而不是模式foo。

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

// 属性名或和属性值是一样的可以简写 这里的 { foo } 等同于 { foo: foo} 

const user = { userName: "jack", password: '123456', age: 18 }

const { password, ...result } = user;

// result { userName: "jack", age: 18 } 

字符串的解构赋值

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

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

解构赋值的规则是,只要等号右边的值不是对象或数组,就先将其转为对象。由于undefinednull无法转为对象,所以对它们进行解构赋值,都会报错。

用途

1、交换变量的值

let x = 1;
let y = 2;

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

2、从函数返回多个值


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

// 返回一个对象

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

3、提取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]

4、遍历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) {
  // ...
}

5、输入模块的指定属性

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