引自http://es6.ruanyifeng.com/#docs/destructuring

  • 数组解构赋值
  • 默认值
  • 对象解构赋值
  • 用途

1.数组的解构赋值

let [a, b, c] = [1, 2, 3];
let [foo, [[bar], baz]] = [1, [[2], 3]];
foo //
bar //
baz // let [ , , third] = ["foo", "bar", "baz"];
third // "baz" let [x, , y] = [1, 2, 3];
x //
y // let [head, ...tail] = [1, 2, 3, 4];
head //
tail // [2, 3, 4] let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []

因为等号右边的值,要么转为对象以后不具备 Iterator 接口(前五个表达式),要么本身就不具备 Iterator 接口(最后一个表达式)。

2.默认值

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] = [null];
x // null let [x = 1, y = x] = [2]; // x=2; y=2

3.对象的解释构

let { bar, foo } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb" var { foo: baz } = { foo: 'aaa', bar: 'bbb' };
baz // "aaa" let obj = {};
let arr = [];
({ foo: obj.prop, bar: arr[0] } = { foo: 123, bar: true });
obj // {prop:123}
arr // [true]

4.用途

(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)函数参数的定义

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

(4)提取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]

(5)函数参数的默认值

jQuery.ajax = function (url, {
async = true,
beforeSend = function () {},
cache = true,
complete = function () {},
crossDomain = false,
global = true,
// ... more config
}) {
// ... do stuff
};

(6)遍历Map结构

var 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. [蟒蛇菜谱]Python日志记录最佳实践
  2. CSS子元素居中(父元素宽高已知,子元素未知)
  3. linux source与 . 命令
  4. debian linux 下安装 netbeans(php)
  5. ssh 配置自动登录
  6. Iaas-cloudstack
  7. java异常处理机制throw
  8. 关于NoSQL数据库你应该知道的10件事
  9. Call an activity method from a fragment
  10. 关于GPL329A中获取摄像头sensor id的问题
  11. Python面向对象之反射
  12. Mvc Swagger报错的解决办法。
  13. adb server is out of date. killing... ADB server didn't ACK解决方法
  14. HashMap底层实现原理
  15. C#本质论第四版-1,抄书才能看下去,不然两三眼就看完了,一摞书都成了摆设。抄下了记忆更深刻
  16. 「美团外卖APP签约快捷支付」流程体验
  17. seo优化之域名泛解析优缺点分析
  18. Redis 与Spring-data-redis 整合后封装的工具类
  19. 谷歌的java文本差异对比工具
  20. Python中__init__()方法注意点

热门文章

  1. leetcode-212-单词搜索②
  2. [JZOJ3337] 【NOI2013模拟】wyl8899的TLE
  3. 修改web项目的启动页
  4. 获取AndroidManifest.xml中的meta-data元素
  5. 三种方法实现MNIST 手写数字识别
  6. STL容器set用法以及codeforces 685B
  7. Eclips安装STS(Spring Tool Suite (STS) for Eclipse)插件
  8. 初识OpenCV-Python - 004: Trackbar as the color palette
  9. uoj#370【UR #17】滑稽树上滑稽果
  10. NEERC 2015 Adjustment Office /// oj25993