5 分鐘掌握 JavaScript 實用竅門(轉自公眾號《前端開發》)
1. 刪除數組尾部元素
一個簡單方法就是改變數組的length值:
const arr = [11, 22, 33, 44, 55, 66];
// truncanting
arr.length = 3;
console.log(arr); //=> [11, 22, 33]
// clearing
arr.length = 0;
console.log(arr); //=> []
console.log(arr[2]); //=> undefined
2. 使用對象解構(object destructuring)來模擬命名參數
如果需要將一系列可選項作為參數傳入函數,你很可能會使用對象(Object)來定義配置(Config)。
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 中的命名參數。
在 ES 2015 中,你可以直接使用對象解構:
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(‘,‘);
4. 在 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. await 多個 async 函數
在使用 async/await 的時候,可以使用 Promise.all 來 await 多個 async 函數
await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])
6. 創建 pure objects
你可以創建一個 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. 從數組中移除重復元素
通過使用集合語法和 Spread 操作,可以很容易將重復的元素移除:
const removeDuplicateItems = arr => [...new Set(arr)];
removeDuplicateItems([42, ‘foo‘, 42, ‘foo‘, true, true]);
//=> [42, "foo", true]
9. 平鋪多維數組
使用 Spread 操作平鋪嵌套多維數組:
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]
5 分鐘掌握 JavaScript 實用竅門(轉自公眾號《前端開發》)