摘要:本文通過實例簡單介紹了ES6中有用的10個功能,以鼓勵讀者盡快深入研究并熟悉ES6。以下是譯文。

雖然ES6的規范并不是特別地新,但我認為很多開發人員對其仍然不太熟悉。 主要原因在于Web瀏覽器的支持可能比較差。目前,該規范發布已經有兩年多了,很多瀏覽器對ES6的支持還算不錯。 即使不使用新版本的Web瀏覽器,也可以在應用程序的構建過程中使用代碼轉譯工具(如Babel)將ES6的源代碼轉換為ES5的源代碼。 趕快提升自己,學習ES6吧。
本文盡可能簡單地介紹了ES6中有用的功能。 在閱讀完本教程之后,你就可以把學到的這些基本技能應用到實際項目中去了。本文并不是指南或說明文檔。本文的目標是鼓勵讀者深入研究并熟悉ES6。
const用于定義常量。 let用于定義變量。但是JavaScript中不是已經有變量了嗎? 是的,這很正確,但用var聲明的變量具有函數作用域,并會被提升到頂部。 這意味著在聲明之前就可以使用這個變量。 let變量和常量具有塊作用域(用{}包圍),在聲明之前不能被使用。
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()
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
非常酷的助手函數出現了。像這樣的邏輯你實現了多少次了:過濾,檢查是否有元素滿足條件,然后進行元素轉換。也許有無數次吧。現在,有一些非常強大的功能可以代替你做這些事情。在我看來,這些是有價值的功能:
forEach
對數組的每個元素執行所提供的函數,將數組元素作為參數傳遞進入。
var colors = ['red', 'green', 'blue'] function print(val) { console.log(val)
}
colors.forEach(print)
red
green
blue
map
創建一個包含相同數量元素的新數組,但是由提供的函數創建輸出元素。它只是將數組中的每個元素做了轉換。
var colors = ['red', 'green', 'blue'] function capitalize(val) { return val.toUpperCase()
} var capitalizedColors = colors.map(capitalize)
console.log(capitalizedColors)
["RED","GREEN","BLUE"]
filter
創建一個包含原始數組子集的新數組。新數組的元素則是那些通過了所提供函數測試的元素,測試函數應返回true或false。
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。
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。
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
個參數是一個函數,該函數的參數為一個累加器以及數組中的每個元素(從左到右),并終輸出單個值。累加器的初始值則由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
有時候,實現一些簡單的功能也需要編寫大量的重復代碼。有什么補救辦法嗎?有,請嘗試一下箭頭函數!
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)
當轉移到JS項目的時候,哪個Java開發人員不會錯過類?誰不喜歡像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'))
console.log('The default color point is ' + ColorPoint.default())
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]
對象字面量已得到了增強。現在我們可以更容易地:
- 定義具有相同名稱的變量賦值字段
- 定義函數
- 定義動態屬性
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
誰喜歡寫一連串的字符串與變量的連接?我相信只有極少數人會喜歡。誰討厭閱讀這樣的連接?每個人。幸運的是,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?
請注意,我們可以將文本寫成多行。
重要提示:請使用反引號而不是撇號來將文本包圍起來。
你不喜歡提供所有可能的函數參數?請使用默認值。
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
Spread
它可以將數組或對象內容提取為單個元素。
示例 - 數組的淺拷貝:
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
對于數組
從數組中提取指定元素并將其賦值給變量。
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
Promise承諾,你將會得到延時任務或者長期運行任務的未來結果。Promise有兩個通道:個為結果,第二個為潛在的錯誤。要獲取結果,你要將回調函數作為“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
本站文章版權歸原作者及原出處所有 。內容為作者個人觀點, 并不代表本站贊同其觀點和對其真實性負責,本站只提供參考并不構成任何投資及應用建議。本站是一個個人學習交流的平臺,網站上部分文章為轉載,并不用于任何商業目的,我們已經盡可能的對作者和來源進行了通告,但是能力有限或疏忽,造成漏登,請及時聯系我們,我們將根據著作權人的要求,立即更正或者刪除有關內容。本站擁有對此聲明的最終解釋權。