[譯] 5 分鐘學習一些優雅的 JavaScript 技巧
原文: ofollow,noindex">Learn these neat JavaScript tricks in less than 5 minutes
作者:Alcides Queiroz
5 分鐘學習一些優雅的 JavaScript 技巧 —— 專業的省時技巧
1. 清空或擷取陣列
一個簡單的清空或者擷取陣列的方法,就是修改它的 length
屬性:
const arr = [11, 22, 33, 44, 55, 66]; // 擷取 arr.length = 3; console.log(arr); //=> [11, 22, 33] // 清空 arr.length = 0; console.log(arr); //=> [] console.log(arr[2]); //=> undefined
2.用物件解構來模擬引數命名
當你要給函式傳入帶有一系列配置的引數時,你很可能會使用配置物件的方法,例如:
doSomething({ foo: 'Hello', bar: 'Hey!', baz: 42 }); function doSomething(config) { const foo = config.foo !== undefined ? config.foo : 'Hi'; const bar = config.bar !== undefined ? config.bar : 'Yo!'; const baz = config.baz !== undefined ? config.baz : 13; // ... }
在 JavaScript 中模擬命名引數,是一個陳舊但是很有效的方式。這樣函式呼叫看起來舒服多了。另一方面,配置物件的控制邏輯也不需要這麼冗長,使用 ES2015 的物件解構,可以避免這個問題:
function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 }) { // ... }
如果你想讓配置物件是可選的,也很簡單:
function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 } = {}) { // ... }
3.對陣列使用物件解構
使用物件解構把陣列項賦值給特定的變數:
const csvFileLine = '1997,John Doe,US,[email protected],New York'; const { 2: country, 4: state } = csvFileLine.split(',');
譯註:這裡把陣列下標為 2 的值( US
)賦給變數 country
; 下標為 4 的值( New York
)賦給變數 state
。
4. switch 中使用範圍
注意:經過一番思考,我決定把這個技巧和文中其他的區別開來。這個並不是一個節約時間的技巧,在真正程式碼中也不適合使用。記住:這種場景下使用 if
通常會更好。
和文中其他的技巧不同,這個方法主要是為了好奇而不是實用。
總之,由於歷史原因我會保留這個技巧在這篇文章中。
這裡有個簡單的在 switch 語句中使用範圍的技巧:
function getWaterState(tempInCelsius) { let state; switch (true) { case (tempInCelsius <= 0): state = 'Solid'; break; case (tempInCelsius > 0 && tempInCelsius < 100): state = 'Liquid'; break; default: state = 'Gas'; } return state; }
5. 使用 async/await
時, await
多個 async
函式
可以使用 Promise.all
來 await
多個 async 函式執行完成:
await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])
6. 建立純物件
你可以建立 100% 的純物件(pure object), 不繼承 Object
的任何屬性和方法(例如: constructor
、 toString()
等等)。
const pureObject = Object.create(null); console.log(pureObject); //=> {} console.log(pureObject.constructor); //=> undefined console.log(pureObject.toString); //=> undefined console.log(pureObject.hasOwnProperty); //=> undefined
7. 格式化 JSON 程式碼
JSON.stringify
能做的不只是簡單的字串化物件,你還可以使用它來格式化 JSON 的輸出:
const obj = { foo: { bar: [11, 22, 33, 44], baz: { bing: true, boom: 'Hello' } } }; // The third parameter is the number of spaces used to // beautify the JSON output. JSON.stringify(obj, null, 4); // =>"{ // =>"foo": { // =>"bar": [ // =>11, // =>22, // =>33, // =>44 // =>], // =>"baz": { // =>"bing": true, // =>"boom": "Hello" // =>} // =>} // =>}"
8. 陣列去重
只使用 ES2015 的 Set
和展開運算子,就可以輕鬆實現陣列去重:
const removeDuplicateItems = arr => [...new Set(arr)]; removeDuplicateItems([42, 'foo', 42, 'foo', true, true]); //=> [42, "foo", true]
9.扁平化多維陣列
使用展開運算子可以輕鬆的扁平化陣列:
const arr = [11, [22, 33], [44, 55], 66]; const flatArr = [].concat(...arr); //=> [11, 22, 33, 44, 55, 66]
可惜的是,上面的這個技巧只對二維陣列有效。但是通過遞迴,我們可以使它也適用於二維以上的陣列:
function flattenArray(arr) { const flattened = [].concat(...arr); return flattened.some(item => Array.isArray(item)) ? flattenArray(flattened) : flattened; } const arr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]]; const flatArr = flattenArray(arr); //=> [11, 22, 33, 44, 55, 66, 77, 88, 99]
就這些啦!希望這些優雅的小技巧可以幫你寫出更好更漂亮的 JavaScript。