您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

ES6中超实用的几个技巧总结

2025/12/29 12:01:03发布23次查看
本篇文章给大家带来的内容是关于es6中超实用的几个技巧总结,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
hack #1 交换元素
利用 数组解构来实现值的互换
let a = 'world', b = 'hello'[a, b] = [b, a]console.log(a) // -> helloconsole.log(b) // -> world
hack #2 调试
我们经常使用 console.log()来进行调试,试试 console.table()也无妨。
const a = 5, b = 6, c = 7console.log({ a, b, c });console.table({a, b, c, m: {name: 'xixi', age: 27}});
hack #3 单条语句
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
hack #4 数组拼接
展开运算符可以取代 concat的地位了
const one = ['a', 'b', 'c']const two = ['d', 'e', 'f']const three = ['g', 'h', 'i']const result = [...one, ...two, ...three]
hack #5 制作副本
我们可以很容易的实现数组和对象的 浅拷贝
const obj = { ...oldobj }const arr = [ ...oldarr ]
hack #6 命名参数
解构使得函数声明和函数的调用更加可读
// 我们尝尝使用的写法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 })
hack #7 async/await结合数组解构
数组解构非常赞!结合 promise.all和 解构和 await会使代码变得更加的简洁
const [user, account] = await promise.all([ fetch('/user'), fetch('/account')])
以上就是es6中超实用的几个技巧总结的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product