舉例說明了十大ES6功能

雖然ES6規範不是最近才發佈,但我認爲不少開發人員仍然不太熟悉。 主要緣由是在規範發佈以後,Web瀏覽器的支持可能不好。 目前,規範發佈已經超過2年了,如今不少瀏覽器對ES6支持良好。 即便您(或您的客戶)不使用最新版本的Web瀏覽器,也可使用轉換器(如Babel),在應用程序的構建過程當中將ES6轉換爲ES5。 這意味着要向前邁出一步,學習ES6。git

在本文中,我將盡可能簡單地介紹最有用的功能。 在本教程以後,您將擁有基本技能,並可以將其應用於實際項目中。 不要將其視爲指南或文件。 個人目標是鼓勵你深刻挖掘並熟悉ES6。es6

1. const和let關鍵字

const使您可以定義常量(最終變量!)。 let讓你定義變量。 這很棒,可是JavaScript中沒有變量嗎? 是有的,可是由var聲明的變量具備函數範圍,並被提高到頂部。 這意味着在聲明以前可使用一個變量。 讓變量和常量具備塊範圍(由{}包圍),在聲明以前不能使用。github

function f() {
  var x = 1
  let y = 2
  const z = 3
  {
    var x = 100
    let y = 200
    const z = 300
    console.log('x in block scope is', x)
    console.log('y in block scope is', y)
    console.log('z in block scope is', z)
  }
  console.log('x outside of block scope is', x)
  console.log('y outside of block scope is', y)
  console.log('z outside of block scope is', z)
}

f()

運行結果以下:api

x in block scope is 100 
y in block scope is 200 
z in block scope is 300 
x outside of block scope is 100 
y outside of block scope is 2 
z outside of block scope is 3

2. 數組輔助方法

出現了新的很酷的功能,這有助於在不少狀況下使用JS Array。 您實現了多少次的邏輯,如:過濾,檢查是否有任何或全部元素符合條件,或者元素轉換? 是否是不少種情景下都有用過? 如今語言自己自帶這些很好用的功能。 在我看來,這是最有價值的功能:數組

forEach

對數組的每一個元素執行傳入的函數,將數組元素做爲參數傳遞。瀏覽器

var colors = ['red', 'green', 'blue']

function print(val) {
  console.log(val)
}

colors.forEach(print)

運行結果以下:less

red 
green 
blue

map

建立一個包含相同數量元素的新數組,可是由傳入的函數返回元素。 它只是將每一個數組元素轉換成別的東西。dom

var colors = ['red', 'green', 'blue']

function capitalize(val) {
    return val.toUpperCase()
}

var capitalizedColors = colors.map(capitalize)

console.log(capitalizedColors)

運行結果以下:async

["RED","GREEN","BLUE"]

filter

建立一個包含原始數組子集的新數組。 新數組包含的這些元素經過由傳入的函數實現的測試,該函數應該返回true或false。ide

var values = [1, 60, 34, 30, 20, 5]

function lessThan20(val) {
    return val < 20
}

var valuesLessThan20 = values.filter(lessThan20)

console.log(valuesLessThan20)

運行結果以下:

[1,5]

find

找到經過傳入的函數測試的第一個元素,該函數應該返回true或false。

var people = [
  {name: 'Jack', age: 50},
  {name: 'Michael', age: 9}, 
  {name: 'John', age: 40}, 
  {name: 'Ann', age: 19}, 
  {name: 'Elisabeth', age: 16}
]

function teenager(person) {
    return person.age > 10 && person.age < 20
}

var firstTeenager = people.find(teenager)

console.log('First found teenager:', firstTeenager.name)

運行結果以下:

First found teenager: Ann

every

檢查數組的每一個元素是否經過傳入函數的測試,該函數應該返回true或false(每一個函數都返回true,則結果爲true,不然爲false)。

var people = [
  {name: 'Jack', age: 50},
  {name: 'Michael', age: 9}, 
  {name: 'John', age: 40}, 
  {name: 'Ann', age: 19}, 
  {name: 'Elisabeth', age: 16}
]

function teenager(person) {
    return person.age > 10 && person.age < 20
}

var everyoneIsTeenager = people.every(teenager)

console.log('Everyone is teenager: ', everyoneIsTeenager)

運行結果以下:

Everyone is teenager:  false

some

檢查數組的任何元素是否經過由提供的函數實現的測試,該函數應該返回true或false。(有一個函數返回true,則結果true。不然結果爲false)

var people = [
  {name: 'Jack', age: 50},
  {name: 'Michael', age: 9}, 
  {name: 'John', age: 40}, 
  {name: 'Ann', age: 19}, 
  {name: 'Elisabeth', age: 16}
]

function teenager(person) {
    return person.age > 10 && person.age < 20
}

var thereAreTeenagers = people.some(teenager)

console.log('There are teenagers:', thereAreTeenagers)

運行結果以下:

There are teenagers: true

reduce

方法接收一個函數做爲累加器(accumulator),數組中的每一個值(從左到右)開始縮減,最終爲一個值。 累加器的初始值應做爲reduce函數的第二個參數提供。

var array = [1, 2, 3, 4]

function sum(acc, value) {
  return acc + value
}

function product(acc, value) {
  return acc * value
}

var sumOfArrayElements = array.reduce(sum, 0)
var productOfArrayElements = array.reduce(product, 1)

console.log('Sum of', array, 'is', sumOfArrayElements)
console.log('Product of', array, 'is', productOfArrayElements)

運行結果以下:

Sum of [1,2,3,4] is 10 
Product of [1,2,3,4] is 24

3.箭頭函數

執行很是簡單的函數(如上述的SumProduct)須要編寫大量的模版。 有什麼解決辦法嗎? 是的,能夠嘗試箭頭函數!

var array = [1, 2, 3, 4]

const sum = (acc, value) => acc + value
const product = (acc, value) => acc * value

var sumOfArrayElements = array.reduce(sum, 0)
var productOfArrayElements = array.reduce(product, 1)

箭頭函數也能夠內聯。 它真的簡化了代碼:

var array = [1, 2, 3, 4]

var sumOfArrayElements = array.reduce((acc, value) => acc + value, 0)
var productOfArrayElements = array.reduce((acc, value) => acc * value, 1)

箭頭函數也能夠更復雜,而且有不少行代碼:

var array = [1, 2, 3, 4]

const sum = (acc, value) => {
  const result = acc + value
  console.log(acc, ' plus ', value, ' is ', result)
  return result
}

var sumOfArrayElements = array.reduce(sum, 0)

4. 類

哪一個Java開發人員在切換到JS項目時不會錯過類? 誰不喜歡顯式繼承,像Java語言,而不是爲原型繼承編寫魔術代碼? 這引發了一些JS開發者反對,由於在ES6中已經引入了類。 他們不改變繼承的概念。 它們只是原型繼承的語法糖。

class Point {
    constructor(x, y) {
        this.x = x
        this.y = y
    }

    toString() {
        return '[X=' + this.x + ', Y=' + this.y + ']'
    }
}

class ColorPoint extends Point {
    static default() {
        return new ColorPoint(0, 0, 'black')
    }

    constructor(x, y, color) {
        super(x, y)
        this.color = color
    }

    toString() {
        return '[X=' + this.x + ', Y=' + this.y + ', color=' + this.color + ']'
    }
}

console.log('The first point is ' + new Point(2, 10))
console.log('The second point is ' + new ColorPoint(2, 10, 'green'))

運行結果以下:

The first point is [X=2, Y=10] 
The second point is [X=2, Y=10, color=green] 
The default color point is [X=0, Y=0, color=black]

5.對象功能加強

對象功能已被加強。 如今咱們能夠更容易地:

  1. 定義具備和已有變量名稱相同且賦值的字段
  2. 定義函數
  3. 定義動態(計算)屬性
const color = 'red'
const point = {
  x: 5,
  y: 10,
  color,
  toString() {
    return 'X=' + this.x + ', Y=' + this.y + ', color=' + this.color
  },
  [ 'prop_' + 42 ]: 42
}

console.log('The point is ' + point)
console.log('The dynamic property is ' + point.prop_42)

運行結果以下:

The point is X=5, Y=10, color=red 
The dynamic property is 42

6. 模板字符串

誰喜歡寫大字符串和變量鏈接? 我相信咱們中只有少數人喜歡。 誰討厭閱讀這樣的代碼? 我肯定你們都是,ES6引入了很是易於使用的字符串模板和變量的佔位符。

function hello(firstName, lastName) {
  return `Good morning ${firstName} ${lastName}! 
How are you?`
}

console.log(hello('Jan', 'Kowalski'))

運行結果以下:

Good morning Jan Kowalski! 
How are you?

請注意,咱們能夠寫多行文本。

重要提示:使用反引號代替撇號來包裝文本。

7. 默認函數參數

你不喜歡提供全部可能的函數參數? 使用默認值。

function sort(arr = [], direction = 'ascending') {
  console.log('I\'m going to sort the array', arr, direction)
}

sort([1, 2, 3])
sort([1, 2, 3], 'descending')

運行結果以下:

I'm going to sort the array [1,2,3] ascending 
I'm going to sort the array [1,2,3] descending

8. rest參數和擴展運算符

擴展

它能夠將數組或對象內容提取爲單個元素。

示例 - 製做數組的淺拷貝:

var array = ['red', 'blue', 'green']
var copyOfArray = [...array]

console.log('Copy of', array, 'is', copyOfArray)
console.log('Are', array, 'and', copyOfArray, 'same?', array === copyOfArray)

運行結果以下:

Copy of ["red","blue","green"] is ["red","blue","green"] 
Are ["red","blue","green"] and ["red","blue","green"] same? false

示例 - 合併數組:

var defaultColors = ['red', 'blue', 'green']
var userDefinedColors = ['yellow', 'orange']

var mergedColors = [...defaultColors, ...userDefinedColors]

console.log('Merged colors', mergedColors)

運行結果以下:

Merged colors ["red","blue","green","yellow","orange"]

rest參數

您要將前幾個函數參數綁定到變量,其餘變量做爲數組綁定到單個變量嗎? 如今你能夠很容易地作到這一點。

function printColors(first, second, third, ...others) {
  console.log('Top three colors are ' + first + ', ' + second + ' and ' + third + '. Others are: ' + others)
}
printColors('yellow', 'blue', 'orange', 'white', 'black')

運行結果以下:

Top three colors are yellow, blue and orange. Others are: white,black

9. 解構賦值

數組

從數組中提取所請求的元素並將其分配給變量。

function printFirstAndSecondElement([first, second]) {
    console.log('First element is ' + first + ', second is ' + second)
}

function printSecondAndFourthElement([, second, , fourth]) {
    console.log('Second element is ' + second + ', fourth is ' + fourth)
}

var array = [1, 2, 3, 4, 5]

printFirstAndSecondElement(array)
printSecondAndFourthElement(array)

運行結果以下:

First element is 1, second is 2 
Second element is 2, fourth is 4

對象

從對象中提取所請求的屬性,並將其分配給與屬性相同名稱的變量。

function printBasicInfo({firstName, secondName, profession}) {
    console.log(firstName + ' ' + secondName + ' - ' + profession)
}

var person = {
  firstName: 'John',
  secondName: 'Smith',
  age: 33,
  children: 3,
  profession: 'teacher'
}

printBasicInfo(person)

運行結果以下:

John Smith - teacher

10. Promises

Promises承諾(是的,我知道這聽起來很奇怪),你將會獲得延期或長期運行任務的將來結果。 承諾有兩個渠道:第一個爲結果,第二個爲潛在的錯誤。 要獲取結果,您將回調函數做爲「then」函數參數。 要處理錯誤,您將回調函數提供爲「catch」函數參數。

function asyncFunc() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
          const result = Math.random();
          result > 0.5 ? resolve(result) : reject('Oppps....I cannot calculate')
        }, 1)
    });
}

for (let i=0; i<10; i++) {
    asyncFunc()
        .then(result => console.log('Result is: ' + result))
        .catch(result => console.log('Error: ' + result))
}

運行結果以下:

Result is: 0.7930997430022211 
Error: Oppps....I cannot calculate 
Result is: 0.6412258210597288 
Result is: 0.7890325910244533 
Error: Oppps....I cannot calculate 
Error: Oppps....I cannot calculate 
Result is: 0.8619834683310168 
Error: Oppps....I cannot calculate 
Error: Oppps....I cannot calculate 
Result is: 0.8258410427354488

總結

我但願你喜歡這篇文章。 若是您想要一些練習,您可使用沙箱進行學習過程:https://es6console.com/。 若是您須要更多信息,能夠在這裏找到

翻譯自Top 10 ES6 features by example

關注個人公衆號,更多優質文章定時推送

clipboard.png

相關文章
相關標籤/搜索