Skip to content

变量的解构赋值

从数组和对象中提取值,对变量进行赋值。

javascript
let [a, b, c] = [1, 2, 3];
//等价于
let a = 1;
let b = 2;
let c = 3;

这种写法也属于"模式匹配"。

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

如果解构不成功,变量的值就等于 undefined

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

也可以不完全解构,左边只匹配一部分右边的数组。

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

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

等号的右边不是数组(不可遍历的结构),那就会报错。但对于 set 结构,也可以使用数组的解构赋值

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

默认值

解构赋值允许指定默认值,只有数组成员严格等于undefined,默认值才会生效,null 不严格等于 undefined

javascript
let [foo=true] = []
foo //true
let [x,y='b'] = ['a'] //x='a' y='b'
let [x,y='b'] = ['a',undefined] //x='a' y='b'
let [x = 1] = [undefined];
x // 1

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

对象的解构赋值

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

对象的解构和数组有不通过,数组的元素是按照次序排列,变量由位置决定。而对象的属性没次序,变量等必须与属性同名,才能取到正确的值。

javascript
let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
//解构失败 变量的值为undefined
let { baz } = { foo: 'aaa', bar: 'bbb' };
baz // undefined

可以对现有对象的方法,赋值到某个变量。

javascript
let { log, sin, cos } = Math;
// 例二
const { log } = console;
log('hello') // hello

若变量名与属性名不一致,改写如下:

javascript
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'

解构也能用于嵌套解构的对象。

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

此时的 p 是模式,不是变量,若要作为变量赋值,改写如下:

javascript
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}

默认值

对象的解构也可以指定默认值。

javascript
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"

它和数组的解构一样,对象的属性也严格等于 undefined

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

数组本质也是特殊的对象,可以对数组进行对象属性的解构。

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

字符串的解构赋值

javascript
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
let {length : len} = 'hello';
len // 5

数值和布尔值的解构赋值

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

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

函数参数的解构赋值

javascript
function add([x, y]){
  return x + y;
}
//
add([1, 2]); // 3
[[1, 2], [3, 4]].map(([a, b]) => a + b);
// [ 3, 7 ]

函数参数的解构使用默认值。

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

当解析失败,xy 等于默认值。

另一种写法:

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

这是对 move 函数的参数指定默认值,不是变量 xy 指定默认值。

切记不能使用圆括号!!!!!!!

用途

  1. 交换变量的值
javascript
let x = 1;
let y = 2;
[x, y] = [y, x];
  1. 从函数返回多个值

通过放在数组或者对象,就能返回多个值。

javascript
// 返回一个数组
function example() {
  return [1, 2, 3];
}
let [a, b, c] = example();
// 返回一个对象
function example() {
  return {
    foo: 1,
    bar: 2
  };
}
let { foo, bar } = example();
  1. 函数参数的定义(参数与变量名对应起来)
javascript
// 参数是一组有次序的值
function f([x, y, z]) { ... }
f([1, 2, 3]);
// 参数是一组无次序的值
function f({x, y, z}) { ... }
f({z: 3, y: 2, x: 1});
  1. 提取 JSON 数据
javascript
let jsonData = {
  id: 42,
  status: "OK",
  data: [867, 5309]
};
let { id, status, data: number } = jsonData;
console.log(id, status, number);
// 42, "OK", [867, 5309]
  1. 函数参数的默认值(不需要在函数体内在重新定义)
javascript
jQuery.ajax = function (url, {
  async = true,
  beforeSend = function () {},
  cache = true,
  complete = function () {},
  crossDomain = false,
  global = true,
  // ... more config
} = {}) {
  // ... do stuff
};
  1. 遍历 Map 结构
javascript
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
//只取键名或只取键值
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
  1. 输入模块的指定方法
javascript
const { SourceMapConsumer, SourceNode } = require("source-map");