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

Summary of several practical tips in ES6 Super

不言
Release: 2018-12-04 17:17:36
forward
2090 people have browsed it

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
Copy after login

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}});
Copy after login

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
Copy after login

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]
Copy after login

Hack #5 Making a copy

We can easily implement arrays and shallow copies of objects

const obj = { ...oldObj }
const arr = [ ...oldArr ]
Copy after login

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 })
Copy after login

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')
])
Copy after login


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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template