[关闭]
@xiaoyixy 2018-11-08T17:06:07.000000Z 字数 4337 阅读 1171

解构赋值语法

Note ES6 ECMAScript6


解构赋值语法是一个 Javascript 表达式,这使得可以将值从数组或属性从对象提取到不同的变量中。

基本语法

  1. var a, b, rest;
  2. [a, b] = [10, 20];
  3. console.log(a); // 10
  4. console.log(b); // 20
  5. [a, b, ...rest] = [10, 20, 30, 40, 50];
  6. console.log(a); // 10
  7. console.log(b); // 20
  8. console.log(rest); // [30, 40, 50]
  9. ({ a, b } = { a: 10, b: 20 });
  10. console.log(a); // 10
  11. console.log(b); // 20
  12. // Stage 3 proposal
  13. ({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40});
  14. console.log(a); // 10
  15. console.log(b); // 20
  16. console.log(rest); //{c: 30, d: 40}

解构数组

  1. // Basic variable assignment
  2. var foo = ['one', 'two', 'three'];
  3. var [one, two, three] = foo;
  4. console.log(one); // "one"
  5. console.log(two); // "two"
  6. console.log(three); // "three"
  7. // Assignment separate from declaration
  8. var a, b;
  9. [a, b] = [1, 2];
  10. console.log(a); // 1
  11. console.log(b); // 2
  12. // Default values
  13. var a, b;
  14. [a=5, b=7] = [1];
  15. console.log(a); // 1
  16. console.log(b); // 7
  17. // Swapping variables
  18. var a = 1;
  19. var b = 3;
  20. [a, b] = [b, a];
  21. console.log(a); // 3
  22. console.log(b); // 1
  23. // Ignoring some returned values
  24. function f() {
  25. return [1, 2, 3];
  26. }
  27. var [a, , b] = f();
  28. console.log(a); // 1
  29. console.log(b); // 3
  30. // ignore all returned values:
  31. [,,] = f();
  32. // Assigning the rest of an array to a variable\
  33. var [a, ...b] = [1, 2, 3];
  34. console.log(a); // 1
  35. console.log(b); // [2, 3]
  36. // 剩余元素必须是数组的最后一个元素
  37. var [a, ...b,] = [1, 2, 3];
  38. // SyntaxError: rest element may not have a trailing comma

解构对象

  1. // Basic assignmentSection
  2. var o = {p: 42, q: true};
  3. var {p, q} = o;
  4. console.log(p); // 42
  5. console.log(q); // true
  1. // Assignment without declarationSection
  2. var a, b;
  3. /*
  4. * 赋值语句周围的(...) 是使用对象字面解构赋值时不需要声明的语法。
  5. * {a, b} = {a: 1, b: 2}不是有效的独立语法,因为左边的{a, b}被认为是一个块而不是对象字面量。
  6. * ({a, b} = {a: 1, b: 2})是有效的语法,它等价于 var {a, b} = {a: 1, b: 2}
  7. */
  8. ({a, b} = {a: 1, b: 2});
  1. // Assigning to new variable names
  2. var o = {p: 42, q: true};
  3. var {p: foo, q: bar} = o;
  4. console.log(foo); // 42
  5. console.log(bar); // true
  1. // Default values
  2. var {a = 10, b = 5} = {a: 3};
  3. console.log(a); // 3
  4. console.log(b); // 5
  1. // Assigning to new variables names and providing default value
  2. var {a: aa = 10, b: bb = 5} = {a: 3};
  3. console.log(aa); // 3
  4. console.log(bb); // 5
  1. // Setting a function parameter's default value
  2. /*
  3. * 函数签名中,解构的左手边被分配给右手边的空对象字面值:
  4. * {size = 'big', cords = {x: 0, y: 0}, radius = 25} = {}
  5. * 也可以在没有右侧分配的情况下编写函数。
  6. * 但是,如果你忽略了右边的赋值,那么函数会在被调用的时候查找至少一个被提供的参数
  7. * 否则会报错:TypeError: Cannot destructure property `a` of 'undefined' or 'null'.
  8. */
  9. function func({a = 'big', b = {x: 0, y: 0}, c = 25} = {}) {
  10. console.log(a, b, c);
  11. // do something
  12. }
  13. func(); // 'big' {x: 0, y: 0} 25
  14. /* Another Pattern */
  15. function move({x, y} = { x: 0, y: 0 }) {
  16. return [x, y];
  17. }
  18. move({x: 3, y: 8}); // [3, 8]
  19. move({x: 3}); // [3, undefined]
  20. move({}); // [undefined, undefined]
  21. move(); // [0, 0]
  22. // undefined will be destructured using default value
  23. [1, undefined, 3].map((x = 'yes') => x);
  24. // [ 1, 'yes', 3 ]
  1. // Nested object and array destructuring(解构嵌套对象和数组)
  2. var metadata = {
  3. title: "Scratchpad",
  4. translations: [
  5. {
  6. locale: "de",
  7. localization_tags: [ ],
  8. last_edit: "2014-04-14T08:43:37",
  9. url: "/de/docs/Tools/Scratchpad",
  10. title: "JavaScript-Umgebung"
  11. }
  12. ],
  13. url: "/en-US/docs/Tools/Scratchpad"
  14. };
  15. var { title: englishTitle, translations: [{ title: localeTitle }] } = metadata;
  16. console.log(englishTitle); // "Scratchpad"
  17. console.log(localeTitle); // "JavaScript-Umgebung"
  1. // For of iteration and destructuring
  2. var people = [
  3. {
  4. name: 'Mike Smith',
  5. family: {
  6. mother: 'Jane Smith',
  7. father: 'Harry Smith',
  8. sister: 'Samantha Smith'
  9. },
  10. age: 35
  11. },
  12. {
  13. name: 'Tom Jones',
  14. family: {
  15. mother: 'Norah Jones',
  16. father: 'Richard Jones',
  17. brother: 'Howard Jones'
  18. },
  19. age: 25
  20. }
  21. ];
  22. for (var {name: n, family: {father: f}} of people) {
  23. console.log('Name: ' + n + ', Father: ' + f);
  24. }
  25. // "Name: Mike Smith, Father: Harry Smith"
  26. // "Name: Tom Jones, Father: Richard Jones"
  1. // Computed object property names and destructuring
  2. let key = 'z';
  3. let {[key]: foo} = {z: 'bar'};
  4. console.log(foo); // "bar"
  1. // Rest in Object destructuring
  2. let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
  3. a; // 10
  4. b; // 20
  5. rest; // { c: 30, d: 40 }
  1. // Existing Object destructuring
  2. let { log, sin, cos, PI } = Math;
  3. sin(PI/2); // 1
  1. // Object destructuring via Array
  2. let arr = [1, 2, 3];
  3. let {0 : first, [arr.length - 1] : last} = arr;
  4. console.log(first) // 1
  5. console.log(last) // 3

解构字符串

  1. // String is converted into a array-like object
  2. const [a, b] = 'he';
  3. a // "h"
  4. b // "e"
  5. // using its length property to destructure
  6. let {length : len} = 'hello';
  7. len // 5

解构数值和布尔值

  1. let {toString: s} = 123;
  2. s === Number.prototype.toString // true
  3. let {toString: s} = true;
  4. s === Boolean.prototype.toString // true
  5. let { prop: x } = undefined; // TypeError: Cannot destructure property `prop` of 'undefined' or 'null'.
  6. let { prop: y } = null; // TypeError: Cannot destructure property `prop` of 'undefined' or 'null'.

扩展:不能使用圆括号的情况

可以使用圆括号的情况只有一种:赋值语句的非模式部分

  1. // 全部报错
  2. let [(a)] = [1];
  3. let {x: (c)} = {};
  4. let ({x: c}) = {};
  5. let {(x: c)} = {};
  6. let {(x): c} = {};
  7. let { o: ({ p: p }) } = { o: { p: 2 } };

函数参数也属于变量声明,因此不能带有圆括号。

  1. // 报错
  2. function f([(z)]) { return z; }
  3. // 报错
  4. function f([z,(x)]) { return x; }
  1. // 全部报错
  2. ({ p: a }) = { p: 42 };
  3. ([a]) = [5];
  4. // 报错
  5. [({ p: a }), { x: c }] = [{}, {}];

参考

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注