解构赋值语法是一种 Javascript 表达式，它使得将值从数组，或属性从对象，提取到不同的变量中，成为可能。

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

## 语法

    var a, b, rest;
    [a, b] = [10, 20];
    console.log(a); // 10
    console.log(b); // 20

    [a, b, ...rest] = [10, 20, 30, 40, 50];
    console.log(a); // 10
    console.log(b); // 20
    console.log(rest); // [30, 40, 50]

    ({ a, b } = { a: 10, b: 20 });
    console.log(a); // 10
    console.log(b); // 20

    // Stage 4（已完成）提案中的特性
    ({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
    console.log(a); // 10
    console.log(b); // 20
    console.log(rest); // {c: 30, d: 40}

## 描述

对象和数组逐个对应表达式，或称对象字面量和数组字面量，提供了一种简单的定义一个特定的数据组的方法。

    var x = [1, 2, 3, 4, 5];

解构赋值使用了相同的语法，不同的是在表达式左边定义了要从原变量中取出什么变量。

    var x = [1, 2, 3, 4, 5];
    var [y, z] = x;
    console.log(y); // 1
    console.log(z); // 2

JavaScript 中，解构赋值的作用类似于 Perl 和 Python 语言中的相似特性。

## 解构数组

### 变量声明并赋值时的解构

    var foo = ["one", "two", "three"];

    var [one, two, three] = foo;
    console.log(one); // "one"
    console.log(two); // "two"
    console.log(three); // "three"

### 变量先声明后赋值时的解构

通过解构分离变量的声明，可以为一个变量赋值。

    var a, b;

    [a, b] = [1, 2];
    console.log(a); // 1
    console.log(b); // 2

### 默认值

为了防止从数组中取出一个值为`undefined`的对象，可以在表达式左边的数组中为任意对象预设默认值。

    var a, b;

    [a=5, b=7] = [1];
    console.log(a); // 1
    console.log(b); // 7

### 交换变量

在一个解构表达式中可以交换两个变量的值。

没有解构赋值的情况下，交换两个变量需要一个临时变量（或者用低级语言中的XOR-swap技巧）。

    var a = 1;
    var b = 3;

    [a, b] = [b, a];
    console.log(a); // 3
    console.log(b); // 1

### 解析一个从函数返回的数组

从一个函数返回一个数组是十分常见的情况。解构使得处理返回值为数组时更加方便。

在下面例子中，要让 `[1, 2]` 成为函数的 `f()` 的输出值，可以使用解构在一行内完成解析。

    function f() {
      return [1, 2];
    }

    var a, b;
    [a, b] = f();
    console.log(a); // 1
    console.log(b); // 2

### 忽略某些返回值

你也可以忽略你不感兴趣的返回值：

    function f() {
      return [1, 2, 3];
    }

    var [a, , b] = f();
    console.log(a); // 1
    console.log(b); // 3

你也可以忽略全部返回值：

    [,,] = f();

### 将剩余数组赋值给一个变量

当解构一个数组时，可以使用剩余模式，将数组剩余部分赋值给一个变量。

    var [a, ...b] = [1, 2, 3];
    console.log(a); // 1
    console.log(b); // [2, 3]

注意：如果剩余元素右侧有逗号，会抛出 `SyntaxError`，因为剩余元素必须是数组的最后一个元素。

    var [a, ...b,] = [1, 2, 3];
    // SyntaxError: rest element may not have a trailing comma

### 用正则表达式匹配提取值

用正则表达式的 `exec()` 方法匹配字符串会返回一个数组，该数组第一个值是完全匹配正则表达式的字符串，然后的值是匹配正则表达式括号内内容部分。解构赋值允许你轻易地提取出需要的部分，忽略完全匹配的字符串——如果不需要的话。

    function parseProtocol(url) {
      var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
      if (!parsedURL) {
        return false;
      }
      console.log(parsedURL); // ["https://developer.mozilla.org/en-US/Web/JavaScript", "https", "developer.mozilla.org", "en-US/Web/JavaScript"]

      var [, protocol, fullhost, fullpath] = parsedURL;
      return protocol;
    }

    console.log(parseProtocol('https://developer.mozilla.org/en-US/Web/JavaScript')); // "https"

## 解构对象

### 基本赋值

    var o = {p: 42, q: true};
    var {p, q} = o;

    console.log(p); // 42
    console.log(q); // true

### 无声明赋值

通过解构，无需声明即可赋值一个变量。

    var a, b;

    ({a, b} = {a: 1, b: 2});

赋值语句周围的 `( ... )` 是使用对象字面解构赋值时不需要声明的语法。`{a, b} = {a: 1, b: 2}` 不是有效的独立语法，因为左边的 `{a, b}` 被认为是一个块而不是对象字面量。然而，`({a, b} = {a: 1, b: 2})` 是有效的，正如 `var {a, b} = {a: 1, b: 2}`

注意：你的`( ... )` 表达式需要一个分号在它前面，否则它也许会被当成上一行中的函数来执行。

However, `({a, b} = {a: 1, b: 2})` is valid, as is `var {a, b} = {a: 1, b: 2}`

Your `( ... )` expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.

### 给新的变量名赋值

可以从一个对象中提取变量并赋值给和对象属性名不同的新的变量名。

    var o = {p: 42, q: true};
    var {p: foo, q: bar} = o;

    console.log(foo); // 42
    console.log(bar); // true

### 默认值

变量可以先赋予默认值。当要提取的对象没有对应的属性，变量就被赋予默认值。

    var {a = 10, b = 5} = {a: 3};

    console.log(a); // 3
    console.log(b); // 5

### 给新的变量命名并提供默认值

一个属性可以是1）从一个对象解构，并分配给一个不同名称的变量，2）分配一个默认值，以防未解构的值是`undefined`。

    var {a:aa = 10, b:bb = 5} = {a: 3};

    console.log(aa); // 3
    console.log(bb); // 5

### 函数参数默认值

#### ES5 版本

    function drawES5Chart(options) {
      options = options === undefined ? {} : options;
      var size = options.size === undefined ? 'big' : options.size;
      var cords = options.cords === undefined ? { x: 0, y: 0 } : options.cords;
      var radius = options.radius === undefined ? 25 : options.radius;
      console.log(size, cords, radius);
      // now finally do some chart drawing
    }

    drawES5Chart({
      cords: { x: 18, y: 30 },
      radius: 30
    });

#### ES2015 版本

    function drawES2015Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {})
    {
      console.log(size, cords, radius);
      // do some chart drawing
    }

    drawES2015Chart({
      cords: { x: 18, y: 30 },
      radius: 30
    });

在上面的`drawES2015Chart`的函数签名中，解构的左手边被分配给右手边的空对象字面值：`{size = 'big', cords = {x: 0, y: 0}, radius = 25} = {}`。你也可以在没有右侧分配的情况下编写函数。但是，如果你忽略了右边的赋值，那么函数会在被调用的时候查找至少一个被提供的参数，而在当前的形式下，你可以直接调用`drawES2015Chart()`而不提供任何参数。如果你希望能够在不提供任何参数的情况下调用该函数，则当前的设计非常有用，而另一种方法在您确保将对象传递给函数时非常有用。

### 解构嵌套对象和数组

    const metadata = {
      title: 'Scratchpad',
      translations: [
        {
          locale: 'de',
          localization_tags: [],
          last_edit: '2014-04-14T08:43:37',
          url: '/de/docs/Tools/Scratchpad',
          title: 'JavaScript-Umgebung'
        }
      ],
      url: '/en-US/docs/Tools/Scratchpad'
    };

    let {
      title: englishTitle, // rename
      translations: [
        {
           title: localeTitle, // rename
        },
      ],
    } = metadata;

    console.log(englishTitle); // "Scratchpad"
    console.log(localeTitle);  // "JavaScript-Umgebung"

### For of 迭代和解构

    var people = [
      {
        name: 'Mike Smith',
        family: {
          mother: 'Jane Smith',
          father: 'Harry Smith',
          sister: 'Samantha Smith'
        },
        age: 35
      },
      {
        name: 'Tom Jones',
        family: {
          mother: 'Norah Jones',
          father: 'Richard Jones',
          brother: 'Howard Jones'
        },
        age: 25
      }
    ];

    for (var {name: n, family: {father: f}} of people) {
      console.log('Name: ' + n + ', Father: ' + f);
    }

    // "Name: Mike Smith, Father: Harry Smith"
    // "Name: Tom Jones, Father: Richard Jones"

### 从作为函数实参的对象中提取数据

    function userId({id}) {
      return id;
    }

    function whois({displayName: displayName, fullName: {firstName: name}}){
      console.log(displayName + " is " + name);
    }

    var user = {
      id: 42,
      displayName: "jdoe",
      fullName: {
          firstName: "John",
          lastName: "Doe"
      }
    };

    console.log("userId: " + userId(user)); // "userId: 42"
    whois(user); // "jdoe is John"

这段代码从user对象中提取并输出`id、``displayName`和`firstName`。

### 对象属性计算名和解构

计算属性名，如object literals，可以被解构。

    let key = "z";
    let { [key]: foo } = { z: "bar" };

    console.log(foo); // "bar"

### 对象解构中的 Rest

Rest/Spread Properties for ECMAScript 提案（阶段 3）将 rest 语法添加到解构中。Rest 属性收集那些尚未被解构模式拾取的剩余可枚举属性键。

    let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
    a; // 10
    b; // 20
    rest; // { c: 30, d: 40 }

### 无效的 JavaScript 标识符作为属性名称

通过提供有效的替代标识符，解构可以与不是有效的JavaScript标识符的属性名称一起使用。

    const foo = { 'fizz-buzz': true };
    const { 'fizz-buzz': fizzBuzz } = foo;

    console.log(fizzBuzz); // "true"

## 规范

Specification | Status | Comment
--- | --- | ---
ECMAScript 2015 (6th Edition, ECMA-262) Destructuring assignment | Standard | Initial definition.
ECMAScript Latest Draft (ECMA-262) Destructuring assignment | Draft |

## 浏览器兼容

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

| Desktop | Mobile | Server
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | Safari on iOS | Samsung Internet | Node.js
Destructuring assignment | Chrome Full support 49 | Edge Full support 14 | Firefox Full support 41 Notes Full support 41 Notes Notes Firefox provided a non-standard destructuring implementation from Firefox 2 to 40. | IE No support No | Opera Full support Yes | Safari Full support 8 | WebView Android Full support 49 | Chrome Android Full support 49 | Edge Mobile Full support 14 | Firefox Android Full support 41 Notes Full support 41 Notes Notes Firefox provided a non-standard destructuring implementation from Firefox 2 to 40. | Opera Android Full support Yes | Safari iOS Full support 8 | Samsung Internet Android Full support 5.0 | nodejs Full support 6.0.0
Computed property names | Chrome Full support 49 | Edge Full support 14 | Firefox Full support 41 | IE No support No | Opera Full support Yes | Safari No support No | WebView Android Full support 49 | Chrome Android Full support 49 | Edge Mobile Full support 14 | Firefox Android Full support 41 | Opera Android Full support Yes | Safari iOS No support No | Samsung Internet Android Full support 5.0 | nodejs Full support Yes
Rest in arrays | Chrome Full support 49 | Edge Full support 14 Disabled Full support 14 Disabled Disabled From version 14: this feature is behind the `Enable experimental Javascript features` preference. | Firefox Full support 41 | IE No support No | Opera Full support Yes | Safari No support No | WebView Android Full support 49 | Chrome Android Full support 49 | Edge Mobile Full support 14 Disabled Full support 14 Disabled Disabled From version 14: this feature is behind the `Enable experimental Javascript features` preference. | Firefox Android Full support 41 | Opera Android Full support Yes | Safari iOS No support No | Samsung Internet Android Full support 5.0 | nodejs Full support 6.0.0
Rest in objects Experimental | Chrome Full support 60 | Edge No support No | Firefox Full support 55 | IE No support No | Opera Full support Yes | Safari Full support 11.1 | WebView Android Full support 60 | Chrome Android Full support 60 | Edge Mobile No support No | Firefox Android Full support 55 | Opera Android Full support Yes | Safari iOS Full support 11.1 | Samsung Internet Android No support No | nodejs Full support 8.3.0

### Legend

Full support
  Full support
No support
  No support
Experimental. Expect behavior to change in the future.
  Experimental. Expect behavior to change in the future.
See implementation notes.
  See implementation notes.
User must explicitly enable this feature.
  User must explicitly enable this feature.

## 相关链接

- 赋值操作符
- "ES6 in Depth: Destructuring" on hacks.mozilla.org

### 译者注：关于 42

为什么在示例代码中出现了那么多 42？如果有什么特别的原因的话，以下是译者的猜测。

- 42#在人类文化中 - 维基百科
- 生命、宇宙以及任何事情的终极答案 - 维基百科
- 42_(number)#The Hitchhiker's Guide to the Galaxy - Wikipedia
- Phrases_from_The_Hitchhiker%27s_Guide_to_the_Galaxy#Answer_to_the_Ultimate_Question_of_Life,_the_Universe,_and_Everything_(42) - Wikipedia