Home  >  Article  >  Web Front-end  >  Summary of several practical tips in ES6 Super

Summary of several practical tips in ES6 Super

不言
不言forward
2018-12-04 17:17:272057browse

This article brings you a summary of several practical skills in ES6 Super. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Hack #1 Exchange elements

Use array destructuring to achieve value exchange

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

Hack #2 Debugging

We often use console.log() for debugging, it doesn’t hurt to try 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 Single statement

In the ES6 era, statements that operate on arrays will be more compact

// 寻找数组中的最大值
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 Array Splicing

The expansion operator can replace concat

const one = ['a', 'b', 'c']
const two = ['d', 'e', 'f']
const three = ['g', 'h', 'i']
const result = [...one, ...two, ...three]

Hack #5 Making a copy

We can easily implement arrays and shallow copies of objects

const obj = { ...oldObj }
const arr = [ ...oldArr ]

Hack #6 Named parameters

Destructuring makes function declarations and function calls more readable

// 我们尝尝使用的写法
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 combined with array destructuring

Array destructuring is great! Combining Promise.all with destructuring and await will make the code more concise

const [user, account] = await Promise.all([
 fetch('/user'),
 fetch('/account')
])


The above is the detailed content of Summary of several practical tips in ES6 Super. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete
Previous article:what is zeptoNext article:what is zepto