ES6中七个“烎技”

2018-01-25  本文已影响0人  癫厨

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 })

上一篇下一篇

猜你喜欢

热点阅读