对象解构

  1. // 对象结构:
  2. let object = {
  3. name: "lch",
  4. age: 18,
  5. city: "shanghai",
  6. birthday: "1996",
  7. sex: "man",
  8. location: {
  9. from: {
  10. x: 100,
  11. y: 100,
  12. },
  13. to: {
  14. x: 456,
  15. y: 345,
  16. },
  17. },
  18. left: "left",
  19. right: "right",
  20. };
  21. ({ left, right } = object); // 解构赋值
  22. const { name, age } = object;
  23. const { city = "fuzhou" } = object; // 给予默认值
  24. const { birthday: myBirthday } = object; // 赋值给本地变量myBirthday
  25. const { sex: mySex = "man" } = object;
  26. const { company = "jd" } = object; // 不存在的变量的默认赋值
  27. const {
  28. location: { from }, //嵌套的结构赋值
  29. } = object;

数组解构

  1. let arr = [
  2. "red",
  3. "blue",
  4. "green",
  5. {
  6. name: "lch",
  7. age: 18,
  8. },
  9. [1, 2, 3],
  10. ];
  11. const [firstColor, , thirdColor] = arr; // 按照位置,变量名任意
  12. const [first, ...args] = arr; // 剩余项,使用...语法
  13. const [...cloneArr] = arr; // 可以用于克隆(浅拷贝)
  14. const [, , , , [one, two, three]] = arr; // 对内部数组的解构
  15. const [, , , , , what = "defaultColor"] = arr; // 若不存在默认赋值生效
  16. let a = 1,
  17. b = 2;
  18. [a, b] = [b, a]; // 方便地交换

参数解构

  1. // 参数解构
  2. let object = {
  3. city: "shanghai",
  4. birthday: "1996",
  5. sex: "man",
  6. };
  7. // 通常可能这样
  8. function getMessage(name, age, object) {
  9. let { city, birthday, sex } = object;
  10. console.log(name, age, city, birthday, sex);
  11. }
  12. // 但能修改为
  13. function MygetMessage(name, age, { city, birthday, sex }={}) {
  14. // 通过赋予默认值{},防止未传递object时变为undefined而出错
  15. console.log(name, age, city, birthday, sex);
  16. }

在项目代码中碰到这样的:

  1. function myfn(params){
  2. const {name} = params;
  3. }
  4. myfn({name});

若name为数组,则传入的就是数组的真实地址(其实和直接传入name也没差):

  1. function myfn(params) {
  2. const { arr } = params;
  3. arr[0] = 999;
  4. }
  5. var arr = [1, 2, 3];
  6. myfn({ arr });
  7. console.log(arr); // [999, 2, 3]

用途

(1)交换变量的值

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

(2)从函数返回多个值

  1. // 返回一个对象
  2. function example() {
  3. return {
  4. foo: 1,
  5. bar: 2
  6. };
  7. }
  8. let { foo, bar } = example();

(3)函数参数的定义

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

(4)提取JSON数据

  1. let jsonData = {
  2. id: 42,
  3. status: "OK",
  4. data: [867, 5309]
  5. };
  6. let { id, status, data: number } = jsonData;

(5)函数参数的默认值
指定参数的默认值,就避免了在函数体内部再写var foo = config.foo || 'default foo';这样的语句。
(6)遍历Map结构
任何部署了 Iterator 接口的对象,都可以用for...of循环遍历。Map 结构原生支持 Iterator 接口,配合变量的解构赋值,获取键名和键值就非常方便。

  1. const map = new Map();
  2. map.set('first', 'hello');
  3. map.set('second', 'world');
  4. for (let [key, value] of map) {
  5. console.log(key + " is " + value);
  6. }

(7)输入模块的指定方法

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