簡(jiǎn)評(píng):ES6(ECMAScript2015)實(shí)際上是一種新的 JavaScript 規(guī)范叶圃,包含了一些很棒的新特性,可以更加方便地實(shí)現(xiàn)很多復(fù)雜的操作践图。
先看一下 ES6 的新特性:
- Default Parameters in ES6(默認(rèn)參數(shù))
- Template Literals in ES6(模板文本)
- Multi-line Strings in ES6(多行字符串)
- Destructuring Assignment in ES6(解構(gòu)賦值)
- Enhanced Object Literals in ES6(增強(qiáng)的對(duì)象文本)
- Arrow Functions in ES6(箭頭函數(shù))
- Promises in ES6
- Block-Scoped Constructs Let and Const(塊作用域構(gòu)造 Let and Const)
- Classes in ES6(類)
- Modules in ES6(模塊)
Hack #1: Swap variables 交換變量
使用 Array Destructuring 交換值
let a = 'world', b = 'hello'
[a, b] = [b, a]
console.log(a) // -> hello
console.log(b) // -> world
// Yes, it's magic
Hack #2?: Async/Await with Destructuring
下面這段代碼可以同時(shí)發(fā)起兩個(gè)異步請(qǐng)求掺冠,把請(qǐng)求結(jié)果分別附到 user 和 account 中
const [user, account] = await Promise.all([
fetch('/user'),
fetch('/account')
])
Hack #3?: ?Debugging
const a = 5, b = 6, c = 7
console.log({ a, b, c })
// outputs this nice object:
// {
// a: 5,
// b: 6,
// c: 7
// }
Hack #4?: One liners
更緊湊的數(shù)組操作語法
// 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
Hack #5?: ?Array concatenation
展開運(yùn)算符可以用來代替 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]
Hack #6?: Cloning
const obj = { ...oldObj }
const arr = [ ...oldArr ]
Hack #7?: Named parameters 參數(shù)命名
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 })
原文鏈接:7 Hacks for ES6 Developers
推薦閱讀:Level UP! 提升你的編程技能