欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

7个ES6的实用技巧分享

程序员文章站 2022-05-04 15:26:53
...
本文主要和大家分享es6的7个实用技巧,非常不错,具有参考借鉴价值,感兴趣的朋友一起学习吧,希望能帮助到大家。

Hack #1 交换元素

利用 数组解构来实现值的互换


let a = 'world', b = 'hello'
[a, b] = [b, a]
console.log(a) // -> hello
console.log(b) // -> world

Hack #2 调试

我们经常使用 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}});

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 命名参数

以上就是7个ES6的实用技巧分享的详细内容,更多请关注其它相关文章!