聊聊ES7與ES8特性

譯者按: 轉眼ES6發佈2年了,是時候瞭解一下ES7ES8特性了!javascript

爲了保證可讀性,本文采用意譯而非直譯,而且對源代碼進行了大量修改。另外,本文版權歸原做者全部,翻譯僅用於學習。node

我曾寫過一篇關於ES6博客《10個最佳ES6特性》,此次我打算聊聊ES7ES8特性。react

ES7只有2個特性:ios

ES8還沒有發佈(2017年1月),下面是它已經完成起草的一些特性:es6

Array.prototype.includes()

不使用ES7

使用indexOf()驗證數組中是否存在某個元素,這時須要根據返回值是否爲**-1**來判斷:axios

let arr = ['react', 'angular', 'vue'];

if (arr.indexOf('react') !== -1)
{
    console.log('React存在');
}

使用ES7

使用includes()驗證數組中是否存在某個元素,這樣更加直觀簡單:數組

let arr = ['react', 'angular', 'vue'];

if (arr.includes('react'))
{
    console.log('React存在');
}

指數操做符

不使用ES7

使用自定義的遞歸函數calculateExponent或者Math.pow()進行指數運算:異步

function calculateExponent(base, exponent)
{
    if (exponent === 1)
    {
        return base;
    }
    else
    {
        return base * calculateExponent(base, exponent - 1);
    }
}

console.log(calculateExponent(7, 3)); // 輸出343
console.log(Math.pow(7, 3)); // 輸出343

使用ES7

使用指數運算符******,就像**+-**等操做符同樣:

console.log(7**3);

Object.values()

不使用ES8

使用Object.keys()遍歷對象的屬性值,須要經過屬性名key去獲取屬性值:

let obj = {a: 1, b: 2, c: 3};

Object.keys(obj).forEach((key) =>
{
    console.log(obj[key]); // 輸出1, 2, 3
});

使用ES8

使用Object.values()遍歷對象的屬性值,無需使用使用屬性名:

let obj = {a: 1, b: 2, c: 3}

Object.keys(obj).forEach((key) =>
{
    console.log(obj[key]); // 輸出1, 2, 3
});

Object.entries()

不使用ES8

使用Object.keys()遍歷對象的屬性名和屬性值:

let obj = {a: 1, b: 2, c: 3};

Object.keys(obj).forEach((key) =>
{
    console.log(key + ": " + obj[key]); // 輸出a: 1, b: 2, c: 3
})

使用ES8

使用Object.entries()遍歷對象的屬性名和屬性值:

let obj = {a: 1, b: 2, c: 3};

Object.entries(obj).forEach(([key, value]) =>
{
    console.log(key + ": " + value); // 輸出a: 1, b: 2, c: 3
})

padStart()

不使用ES8

console.log('0.00')         	
console.log('10,000.00')    
console.log('250,000.00')

輸出結果以下:

0.00
10,000.00
250,000.00

使用ES8

使用padStart()能夠在字符串前面填充指定的字符串:

console.log('0.00'.padStart(20))         	
console.log('10,000.00'.padStart(20))    
console.log('250,000.00'.padStart(20))

輸出結果以下:

0.00
           10,000.00
          250,000.00

padEnd()

不使用ES8

console.log('0.00 ' + '0.00' )         	
console.log('10,000.00 ' + '10,000.00' )    
console.log('250,000.00 ' + '250,000.00')

輸出以下:

0.00 0.00
10,000.00 10,000.00
250,000.00 250,000.00

使用ES8

使用padEnd()能夠在字符串後面填充指定的字符串:

console.log('0.00'.padEnd(20) + '0.00' )         	
console.log('10,000.00'.padEnd(20) + '10,000.00' )    
console.log('250,000.00'.padEnd(20) + '250,000.00')

輸出以下:

0.00                0.00
10,000.00           10,000.00
250,000.00          250,000.00

Object.getOwnPropertyDescriptors()

azatsBooks對象的定義以下:

let azatsBooks = {
    books: ['React Quickly'],
    get latest()
    {
        let numberOfBooks = this.books.length;
        if (numberOfBooks == 0) return undefined;
        return this.books[numberOfBooks - 1];
    }
};

不使用ES8

使用Object.getOwnPropertyDescriptor()獲取單個屬性的屬性描述符。

獲取azatsBooks對象的books屬性的屬性描述符:

console.log(Object.getOwnPropertyDescriptor(azatsBooks, 'books'));

/** 輸出books屬性的屬性描述
[object Object] {
  configurable: true,
  enumerable: true,
  value: ["React Quickly"],
  writable: true
}
**/

獲取azatsBooks對象的lastest方法的屬性描述符:

console.log(Object.getOwnPropertyDescriptor(azatsBooks, 'latest'));

/** 輸出lastest方法的屬性描述
[object Object] {
  configurable: true,
  enumerable: true,
  get: function get latest() {
    let numberOfBooks = this.books.length
    if (numberOfBooks == 0) return undefined
    return this.books[numberOfBooks - 1]
  },
  set: undefined
}
**/

使用ES8

Object.getOwnPropertyDescriptors()至關於Object.getOwnPropertyDescriptor()的複數形式,能夠獲取對象的全部自身屬性的描述符:

console.log(Object.getOwnPropertyDescriptors(azatsBooks))

/** 輸出azatsBooks對象全部自身屬性的屬性描述
[object Object] {
  books: [object Object] {
    configurable: true,
    enumerable: true,
    value: ["React Quickly"],
    writable: true
  },
  latest: [object Object] {
    configurable: true,
    enumerable: true,
    get: function get latest() {
      let numberOfBooks = this.books.length
      if (numberOfBooks == 0) return undefined
      return this.books[numberOfBooks - 1]
    },
    set: undefined
  }
}
**/

函數參數列表結尾容許逗號

不使用ES8

var f = function(a,
  b,
  c,
  d // d以後不能帶逗號
   ) { 
  console.log(d)
}

使用ES8

var f = function(a,
  b,
  c,
  d, // d以後容許帶逗號
) { 
  console.log(d)
}

容許逗號以後,能夠避免一些沒必要要的報錯。(若是你但願實時監控JavaScript應用的錯誤,歡迎無償使用Fundebug)

Async/Await

使用Promise

使用Promise寫異步代碼,會比較麻煩:

axios.get(`/q?query=${query}`)
    .then(response => response.data)
    .then(data =>
    {
        this.props.processfetchedData(data);
    })
    .catch(error => console.log(error));

使用Async/Await

Async/Await使得異步代碼看起來像同步代碼,這正是它的魔力所在:

async fetchData(query) =>
{
    try
    {
        const response = await axios.get(`/q?query=${query}`);
        const data = response.data;
        return data;
    }
    catch (error)
    {
        console.log(error)
    }
}

fetchData(query).then(data =>
{
    this.props.processfetchedData(data)
})

Async/Await是寫異步代碼的新方式,之前的方法有回調函數Promise。相比於Promise,它更加簡潔,而且處理錯誤、條件語句、中間值都更加方便,所以有望替代Promise,成爲新一代的一步代碼編寫方式。對細節感興趣的話,能夠查看Fundebug翻譯的《Async/Await替代Promise的6個理由》

版權聲明:

轉載時請註明做者Fundebug以及本文地址:

https://blog.fundebug.com/2017/08/28/es7-and-es8/

相關文章
相關標籤/搜索