ES6 的幾個小技巧

前言

本文系翻譯自 Check out these useful ECMAScript 2015 (ES6) tips and tricksjavascript

本文首發於我的博客:www.ferecord.com/check-out-t…。如若轉載請附上原文地址,以便更新溯源。html

EcmaScript 2015 (即 ES6) 已經發布兩年多了,它的不少新功能均可以被技巧性的使用。這篇文章把一些小技巧列出來,但願能對你有用。java

1. 強制參數

ES6 提供了默認參數的概念,當函數的參數未傳入或者傳入值爲 undefined 時,會應用參數的默認值。es6

默認值能夠是個表達式,因此咱們能夠將默認值設置爲一個執行函數,若是該參數沒有傳值,就會執行咱們的默認函數:數組

const required = () => {throw new Error('Missing parameter')};

//The below function will throw an error if either "a" or "b" is missing.
const add = (a = required(), b = required()) => a + b;

add(1, 2) //3
add(1) // Error: Missing parameter.
複製代碼

2. 強大的 reduce

reduce 是一個多才多藝的數組方法,請跟隨我看一下。bash

2.1 使用 reduce 替代 map + filter

設想你有這麼個需求:要把數組中的值進行計算後再濾掉一些值,而後輸出新數組。很顯然咱們通常使用 map 和 filter 方法組合來達到這個目的,但這也意味着你須要迭代這個數組兩次。ecmascript

來看看咱們如何使用 reduce 只迭代數組一次,來完成一樣的結果。下面這個例子咱們須要把數組中的值乘 2 ,並返回大於 50 的值:async

const numbers = [10, 20, 30, 40];
const doubledOver50 = numbers.reduce((finalList, num) => {
  
  num = num * 2; //double each number (i.e. map)
  
  //filter number > 50
  if (num > 50) {
    finalList.push(num);
  }
  return finalList;
}, []);

doubledOver50; // [60, 80]
複製代碼

2.2 使用 reduce 檢測括號是否對齊封閉

下面這個例子咱們用 reduce 來檢測一段 string 中的括號是否先後對應封閉。函數

思路是定義一個名爲 counter 的變量,它的初始值爲 0 ,而後迭代字符串,迭代過程當中碰到(就加 1,碰到)就減 1,若是括號先後對應的話,最終couter的值會是 0。post

//Returns 0 if balanced.
const isParensBalanced = (str) => {
  return str.split('').reduce((counter, char) => {
    if(counter < 0) { //matched ")" before "("
      return counter;
    } else if(char === '(') {
      return ++counter;
    } else if(char === ')') {
      return --counter;
    }  else { //matched some other char
      return counter;
    }
    
  }, 0); //<-- starting value of the counter
}

isParensBalanced('(())') // 0 <-- balanced
isParensBalanced('(asdfds)') //0 <-- balanced
isParensBalanced('(()') // 1 <-- not balanced
isParensBalanced(')(') // -1 <-- not balanced
複製代碼

2.3 使用 reduce 計算數組中的重複項

若是你想計算數組中的每一個值有多少重複值,reducer 也能夠快速幫到你。下面的例子咱們計算數組中每一個值的重複數量,並輸出一個對象來展現:

var cars = ['BMW','Benz', 'Benz', 'Tesla', 'BMW', 'Toyota'];
var carsObj = cars.reduce(function (obj, name) { 
   obj[name] = obj[name] ? ++obj[name] : 1;
  return obj;
}, {});

carsObj; // => { BMW: 2, Benz: 2, Tesla: 1, Toyota: 1 }
複製代碼

reduce 的很是強大,建議各位 把 reduce 的介紹通讀一遍:Reduce_MDN

3. 對象解構

3.1 移除對象的多餘屬性

有時你可能但願移除一個對象中的某些屬性,咱們通常會經過迭代這個對象(如 for..in 循環)來移除那些咱們不想要的屬性。實際上咱們能夠經過對象解構的方法將不想要的屬性提取出來,並將想留下來的變量保存在*rest* 參數中。

在下面的這個例子中,咱們從對象中移除_internaltooBig這兩個屬性:

let {_internal, tooBig, ...cleanObject} = {el1: '1', _internal:"secret", tooBig:{}, el2: '2', el3: '3'};

console.log(cleanObject); // {el1: '1', el2: '2', el3: '3'}
複製代碼

3.2 嵌套對象解構

下面的示例中,engine屬性是對象car內的嵌套對象。咱們能夠經過對象解構快速的獲取到engine中的屬性,好比vin:

var car = {
  model: 'bmw 2018',
  engine: {
    v6: true,
    turbo: true,
    vin: 12345
  }
}

const modelAndVIN = ({model, engine: {vin}}) => {
  console.log(`model: ${model} vin: ${vin}`);
}

modelAndVIN(car); // => model: bmw 2018 vin: 12345
複製代碼

3.3 合併對象

ES6 增長了展開運算符(也就是三個點),展開運算符經常用在處理數組解構上,在對象的解構上它也一樣好用。

下面的示例中咱們合併兩個對象,新對象中相同的屬性會被放在後面的對象覆蓋:

let object1 = { a:1, b:2,c:3 }
let object2 = { b:30, c:40, d:50}
let merged = {...object1, ...object2} //spread and re-add into merged

console.log(merged) // {a:1, b:30, c:40, d:50}
複製代碼

4. 使用 Sets 數組去重

使用 Sets 能夠快速給數組去重,由於 Sets 中的值不可重複。

let arr = [1, 1, 2, 2, 3, 3];
let deduped = [...new Set(arr)] // [1, 2, 3]
複製代碼

5. 數組解構

5.1 交換變量的值

let param1 = 1;
let param2 = 2;

//swap and assign param1 & param2 each others values
[param1, param2] = [param2, param1];
console.log(param1) // 2
console.log(param2) // 1
複製代碼

5.2 從函數接受和分配多個值

不少時候你的函數都會將多個數據放在數組內,以返回一個單一值(例如 Promise 函數,它的決議值只能是個單一值),咱們可使用數組解構簡便的從返回結果中獲取這些值。

下面的這個例子中,咱們使用 fetch 發送了兩個請求,並使用 Promise.all() 將兩個結果保存在數組中,函數的執行結果是返回這個數組。

function getFullPost(){
  return Promise.all([
    fetch('/post'),
    fetch('/comments')
  ]);
}


// 在 async 函數中
const [post, comments] = await getFullPost();
複製代碼

本文完。 have a nice day ( ̄▽ ̄)~*

相關文章
相關標籤/搜索