編寫 ES6 的 7 個實用技巧

2022-07-08 17:00:16 字數 1609 閱讀 4006

無腦翻譯走一波~

使用陣列解構交換變數的值

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

[a, b] = [b, a]

console.log(a) // -> hello

console.log(b) // -> world

// yes, it's magic

再強調一遍,陣列解構非常好用。結合async/awaitpromises能讓複雜的流程變得簡單。

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

fetch('/user'),

fetch('/account')

])

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

console.log()

// outputs this nice object:

//

運算元組時,這會讓**結構變得更為緊湊

// 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

使用展開運算子...代替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]

下面的方法用於複製(淺複製)陣列/物件:

const obj = 

const arr = [ ...oldarr ]

解構命名引數,提公升函式宣告和函式呼叫的可讀性:

const getstuffnotbad = (id, force, verbose) => 

const getstuffawesome = () =>

// somewhere else in the codebase... wtf is true, true?

getstuffnotbad(150, true, true)

// somewhere else in the codebase... i ❤ js!!!

getstuffawesome()

閱讀原文:

ES6的7個實用技巧

利用陣列解構來實現值的互換 let a world b hello a,b b,a console.log a hello console.log b world我們經常使用console.log 來進行除錯,試試console.table 也無妨。const a 5,b 6,c 7 console...

ES6 變數的結構賦值用途(實用技巧)

1.交換變數的值 let x 1 let y 2 x,y y,x x 2,y 1 2.從函式返回多個值 函式只能返回乙個值,如果要返回多個值,只能將它們放在陣列或者物件裡返回,有了解構賦值,取出這些值就非常方便了。返回陣列 function example let a,b,c example a 1...

ES6的七個技巧

利用陣列解構來實現值的互換 let a world b hello a,b b,a console.log a hello console.log b world我們經常使用console.log 來進行除錯,試試console.table 也無妨。const a 5,b 6,c 7 console...