ES6的7个实用技巧
交换元素
利用数组解构来实现值的互换
let a = 'world', b = 'hello' [a, b] = [b, a] console.log(a) // -> hello console.log(b) // -> world
调试
我们经常使用console.log()来进行调试,试试console.table()也无妨。
const a = 5, b = 6, c = 7 console.log({ a, b, c }); console.table({a, b, c, m: {name: 'xixi', age: 27}});
单条语句
ES6时代,操作数组的语句将会更加的紧凑
// 寻找数组中的最大值 const max = (arr) => Math.max(...arr); max([123, 321, 32]) // outputs: 321 // 计算数组的总和 const sum = (arr) => arr.reduce((a, b) => (a + b), 0) sum([1, 2, 3, 4]) // output: 10
数组拼接
展开运算符可以取代concat的地位了
const one = ['a', 'b', 'c'] const two = ['d', 'e', 'f'] const three = ['g', 'h', 'i'] const result = [...one, ...two, ...three]
制作副本
我们可以很容易的实现数组和对象的浅拷贝
const obj = { ...oldObj } const arr = [ ...oldArr ]
命名参数
解构使得函数声明和函数的调用更加可读
// 我们尝尝使用的写法 const getStuffNotBad = (id, force, verbose) => { ...do stuff } // 当我们调用函数时, 明天再看,尼玛 150是啥,true是啥 getStuffNotBad(150, true, true) // 看完本文你啥都可以忘记, 希望够记住下面的就可以了 const getStuffAwesome = ({id, name, force, verbose}) => { ...do stuff } // 完美 getStuffAwesome({ id: 150, force: true, verbose: true })
Async/Await结合数组解构
数组解构非常赞!结合Promise.all和解构和await会使代码变得更加的简洁
const [user, account] = await Promise.all([ fetch('/user'), fetch('/account') ])
课程推荐
相关推荐
-
浏览器什么时候会发起网络请求,去加载一张图片? javascript/jquery
2019-8-6
-
vscode js 实用的代码片段 javascript/jquery
2019-5-4
-
我在阿里招前端,我该怎么帮你? javascript/jquery
2020-5-27
-
JS 中几种轻松处理’this’指向方式 javascript/jquery
2020-6-10
-
深入浅出 TCP/IP 协议栈,TCP/IP协议知识科普 javascript/jquery
2019-5-6
-
前端工具集(辅助工具、开发工具、技术栈、学习网站) javascript/jquery
2020-6-12
-
vue2.x学习笔记(三十二) javascript/jquery
2020-7-11
-
知晓云邀你一起「战疫」:疫情相关小程序任一套餐费用全免 javascript/jquery
2020-6-12
-
angular文件上传进度显示 javascript/jquery
2020-7-16
-
JS基础总结(3)——作用域和闭包 javascript/jquery
2020-5-23