变量的解构赋值
使用方法
1234567891011121314151617181920212223242526 | let [a, b, c] = [1, 2, 3]let [foo, [[bar], baz]] = [1, [[2], 3]]let [ , , third] = ['one', 'two', 'three']let [head, ...tail] = [1, 2, 3, 4]// 默认值 匹配到undeined使用默认值let [foo = true] = []// 默认值可以用表达式function () {}let [x = f()] = [1]// 对象键值匹配let {foo, bar} = {foo: 1, bar: 2}let {foo: f, bar: b} = {foo: 1, bar: 2}//这里()是必须的,没有的话{}会被解析成代码块let foo({foo} = {foo: 1}) |
应用
交换变量
12345 | let x = 1let y = 2[x, y] = [y, x] |
JSON解析
123456789101112 | let jsonData = { id: 42, status: "OK", data: [88,10]}let { id , status, data: number} = jsonDataconsole.log(id, status, number)//42, "OK", [88,10] |
函数参数默认值
123456789101112 | jQuery.ajax = function (url, { async = true, beforeSend = function () {}, cache = true, complete = function () {}, crossDomain = false, globa = true, // ... more config}) { // ... do something} |
遍历Map
12345678 | let map = new Map()map.set('first', 'hello')map.set('second', 'world')for (let [key, value] of map) { console.log(key + " is " + value)} |
字符串扩展
补全字符串
123 | '12'.padStart(10, 'YYYY-MM-DD') //'YYYY-MM-12''12'.padEnd(10,'YYYY-MM-DD') //'12YY-MM-DD' |
字符串模板
12345678910111213141516 | let name = "Bob"let time = "today"`Hello ${name}, how are you ${time}?`// 执行模板let str = 'return ' + '`Hello ${name}!`'let func = new Function('name', str)func('Jack') //"Hello Jack!"let str = '(name) => `Hello ${name}!`'let func = eval.call(null,str);func('Jack') //"Hello Jack!" |
标签模板
1234567 | let a = 5;let b = 10;tag`Hello ${ a + b } world ${a * b}`// 等同于tag(['Hello ', ' world', ''], 15, 50) |
参考资料
原文:大专栏 ECMAScript6 学习笔记 一
标签:ECMAScript6,10,bar,name,笔记,学习,let,foo,Hello
来源: https://www.cnblogs.com/petewell/p/11614850.html