省時省力的ES6
人一懶起來啊,簡直是………上一次發文章都是兩個月前了
這次就收集一些ES6中的HACK吧!講真的(會不會是..)…掌握這些技巧。能讓我們少寫很多行程式碼哦
1. 變數交換
let a = 'world', b = 'hello' [a, b] = [b, a] console.log(a) // -> hello console.log(b) // -> world // 雙擊666
2. 接收函式返回的多個結果
使用async/await,函式會把返回值放在一個數組中。使用陣列解構後就可以把返回值直接賦給相應的變數。
const [user, account] = await Promise.all([ fetch('/user'), fetch('/account') ])
3. 字串拼接
let a = 'hello', b = 'world'; let _string = `${a} ${b}` console.log(_string); // "hello world"
4. 函式引數預設值
const notify = (msg, {type='info', timeout, close=true} = {}) => { // display notification console.log(msg, type, timeout, close) } notify('Hi!'); // Hi! info undefined true notify('Hi!', {type: 'error'}); // Hi! error undefined true notify('Hi!', {type: 'warn', close: false}); // Hi! warn undefined false
5. 陣列
程式碼不多一行搞定
// 最大值 const max = (arr) => Math.max(...arr); max([1, 2, 3]) // outputs: 321 // 求和 const sum = (arr) => arr.reduce((a, b) => (a + b), 0) sum([1, 2, 3, 4]) // output: 10 // 拷貝 let array1 = [1, "3", { a: 1}, 666]; let copyArray = [ ...array1 ]; console.log(copyArray) // [1, "3", {…}, 666] // 陣列連線 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. 去重
通過 JavaScript/Reference/Global_Objects/Set" rel="nofollow,noindex" target="_blank">Set 可以輕易的實現陣列去重
function dedupe(array) {
return […new Set(array)];
}
let noDupes = dedupe([1, 2, “a”, “a”, { obj1: 999}, 7, 3, 1], { obj1: 999});
console.log(noDupes); // [1, 2, “a”, { obj1: 999}, 7, 3]
通過陣列建立 Set
會刪除陣列中的重複項,而spread運算子會將 Set
轉換為 Array
7. 強制要求引數
const throwIfMissing = () => { throw new Error('Missing parameter'); } const func = (requiredParam = throwIfMissing()) => { // some implementation }
8. 刪除物件中不需要引數
let { boy1, boy2, ...others } = { boy1: "sunshine", boy2: "sunshine", girl1: "beautiful", girl2: "very beautiful", girl2: "very beautiful", girl2: "very very beautiful" }; console.log(others) // { girl1: "beautiful", girl2: "very beautiful", girl2: "very beautiful", girl2: "very very beautiful"}
9. 動態屬性名
let name = "mael"; let me = { [`${name}`]: name, age: 24 };
10. for 迴圈
let a = ['a', 'b', 'c', 'd' ]; // ES6 for ( var val of a ) { console.log( val ); } // "a" "b" "c" "d" // ES5 for ( var idx in a ) { console.log( idx ); }// 0 1 2 3
11. 定義抽象基類
抽象基類是一種專門用於繼承的類。它不能直接構建。主要用例是繼承的類具有公共介面。但是, class
尚未利用 abstract
關鍵字來建立抽象基類,我們可以使用 new.target
來模擬。
class Note { constructor() { if (new.target === Note) { throw new Error('Note cannot be directly constructed.') } } } class ColorNote extends Note { } let note = new Note();// error! let colorNote = new ColorNote();// ok
12. 定義惰性範圍函式
我們可以使用 generators
來建立一個惰性函式
function* range(start, count) { for (let delta = 0; delta < count; delta++) { yield start + delta; } } for (let teenageYear of range(13, 7)) { console.log(`Teenage angst @ ${teenageYear}!`); }