ES6中七个“烎技”

1-交换变量

通过数组解构完成

let a = 'world', b = 'hello'

[a, b] = [b, a]

console.log(a) ---> hello

console.log(b) ---> world


2- 通过Async-Await解构

通过数组解构与 Async-Await promise配合使用,可以轻松把玩复杂数据流。

const [user, account] = await Promise.all([

  fetch('/user'),

  fetch('/account')

])

 3-Debugging

喜欢用console.log调试的客官们,现在推荐一个更娇羞的小情人console.table

const a = 5, b = 6, c = 7

console.log({ a, b, c })

// outputs this nice object:

{

a: 5,

b: 6,

c: 7

}

 4-一口到底

对喜欢一口到底,爱装BB的,请看下面—不是给你下面吃…

 Find max value

const max = (arr) => Math.max(...arr);

max([123, 321, 32])

// outputs: 321

Sum array

const sum = (arr) => arr.reduce((a, b) => (a + b), 0)

sum([1, 2, 3, 4])

// output: 10


5-数组连接

使用扩展运算符替代concat

const one = ['a', 'b', 'c']

const two = ['d', 'e', 'f']

const three = ['g', 'h', 'i']

Old way #1

const result = one.concat(two, three)

Old way #2

const result = [].concat(one, two, three)

New

const result = [...one, ...two, ...three]

6-克隆新技术

可惜的只是浅克隆

const obj = { ...oldObj }

const arr = [ ...oldArr ]


7-命名参数

为了函数的可读性使用命名参数

const getStuffNotBad = (id, force, verbose) => {

  ...do stuff

}

const getStuffAwesome = ({ id, name, force, verbose }) => {

  ...do stuff

}

// Somewhere else in the codebase... WTF is true, true?

getStuffNotBad(150, true, true)

// Somewhere else in the codebase... I ❤ JS!!!

getStuffAwesome({ id: 150, force: true, verbose: true })

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容