5分鐘掌握JavaScript小技巧

譯者按: 技巧雖好、重在掌握並使用起來!javascript

爲了保證可讀性,本文采用意譯而非直譯。另外,本文版權歸原做者全部,翻譯僅用於學習。java

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)來定義配置(Config)。less

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中的命名參數。不過呢,在doSomething中處理config的方式略顯繁瑣。在ES2015中,你能夠直接使用對象解構。async

function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 }) {
  // ...
}
複製代碼

若是你想讓這個參數是可選的,也很簡單。函數

function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 } = {}) {
  // ...
}
複製代碼

3. 使用對象解構來處理數組

可使用對象解構的語法來獲取數組的元素:學習

const csvFileLine = '1997,John Doe,US,john@doe.com,New York';
const { 2: country, 4: state } = csvFileLine.split(',');
複製代碼

4. 在switch語句中用範圍值

可使用下面的技巧來寫知足範圍值的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函數。ui

await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])
複製代碼

6. 建立一個純(pure)對象

你能夠建立一個100%的純對象,他不從Object中繼承任何屬性或則方法(好比,constructortoString()等等)。this

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中,有了集合的語法。經過使用集合語法和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]
複製代碼

惋惜,上面的方法僅僅適用於二維數組。不過,經過遞歸,咱們能夠平鋪任意維度的嵌套數組。

unction 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]
複製代碼

就這些啦!我但願這些小技巧能夠幫你寫出更加漂亮的JS代碼!若是還不夠,那麼不妨用Fundebug作你的輔助!

精選評論

  • Ethan B Martin: 這個switch的寫法很巧妙,不過不推薦。請不要鼓勵開發者用這種方式去寫JS代碼。咱們曾經有一個工程師這麼寫,後來在代碼review的時候,形成了很大的閱讀苦難。好在咱們及時將其重構爲更加容易讀懂的代碼。不妨對比一下用swtich和if的區別:

    function getWaterState1(tempInCelsius) {
      let state;
      
      switch (true) {
        case (tempInCelsius <= 0): 
          state = 'Solid';
          break;
        case (tempInCelsius < 100): 
          state = 'Liquid';
          break;
        default: 
          state = 'Gas';
      }
      return state;
    }
    function getWaterState2(tempInCelsius) {
      if (tempInCelsius <= 0) {
        return 'Solid';
      }
      if (tempInCelsius < 100) {
        return 'Liquid';
      }
      return 'Gas';
    }
    複製代碼

    第二種寫法有幾點優點: A) 代碼量更少,更加易讀;B) 你不須要聲明一個局部變量,讀者不會一直要去追蹤你如何對這個變量作了更改;C) switch(true)真的會讓人莫名其妙。

  • Flo Sloot: 很棒的文章!不過不推薦第六招,除非你必定要使用。由於它的執行效率很慢,並且佔用空間更大。由於V8並無對空對象作優化。

相關文章
相關標籤/搜索