ES6在ES5的基礎上新增了一系列特性,這裏僅列出經常使用特性html
變量的改變,添加了塊級做用域的概念 let聲明變量(塊級做用域),let是更完美的var,它聲明的全局變量不是全局屬性widow的變量,這便解決了for循環中變量覆蓋的問題 const聲明常量(會計做用域)vue
// var var a = []; for (var index = 0; index < 10; index++) { a[index]=function () { console.log(index);// index會向上查找a做用域的index值 } } console.log(index); // 10 a[6](); // 10 // let const a = []; for (let index = 0; index < 10; index++) { a[index]=function () { console.log(index); } // index只在本輪循環中生效,每一次循環都會新建一個變量 } a[6](); // 6 console.log(index); // index not defined
let str = 'happy'; console.log(str.includes('ha')) // true console.log(str.repeat(3)) // 'happyhappyhappy' console.log(str.startsWith('ha')); // true,參數2爲查找的位置 console.log(str.endsWith('p', 4)); // true,參數2爲查找的字符串長度\
函數能夠像C/C++那樣設置默認參數值,增長數據容錯能力react
function people(name, age) { return { name, age }; }
const people = { name: 'lux', getName () { // 省略冒號(:) 和function關鍵字 console.log(this.name) } }
const obj1 = { a: 1 } const obj = Object.assign({c: 2}, obj1) console.log(obj);
// 對象解構 const people = { name: 'cs', age: 25 } const { name, age } = people; // 'cs', 25
// 數組解構 const arr = [1, 3, 4]; const [a, b, c] = arr; // 1, 3, 4 // rest參數,返回的是一個對象 const obj = {a: 2, b: 3, c: 4, d: 5}; const {a, ...rest} = obj; // 2 { b: 3, c: 4, d: 5 }
// 展開對象(和上面Object.assign()同樣,也是對象合併) const obj = {a: 2, b: 3} console.log({...obj, c: 5});// {a 2, b: 3, c: 5} // 展開數組 const arr = [1, 3, 4] console.log([...arr, 5]); // [1, 3, 4, 5]
Promise做爲ES6的重要特性之一,被ES6列爲正式規範。在控制檯打印出來Promise是一個構造函數。參見:https://www.cnblogs.com/lvdabao/p/es6-promise-1.htmles6
能夠看到上面的Promise自身有咱們經常使用的all、race、resoleve、reject等方法,原型中還有catch、then等方法,因此咱們建立Promise實例時,將then會做爲callback使用,避免回調地獄的出現。算法
// resolve、reject的使用 function getNum() { const randomNum = Math.ceil(Math.random() * 10); return new Promise((resolve, reject) => { if (randomNum > 5) { resolve('大於5'); } else { reject('小於5'); } }) } getNum().then((result) => { console.log('success', result); }).catch((err) => { console.log('err', err); });
使用catch方法和then的第二個參數的效果同樣,可是它還有你另一個做用,那就是在then的第一個resolve回調函數中代碼出錯,不用卡死js的執行,而是會進入到catch中,捕獲err緣由。json
Promise.all的提供了並行的操做能力,而且是在全部的一步操做執行完成後才執行回調。all接收一個數組參數,它會把全部異步操做的結果放進一個數組中傳給then。數組
// all的使用 function async1 () { return new Promise((resolve, reject) => { setTimeout(() => { console.log('async1'); resolve('async1完成') }, 1000); }) } function async2 () { return new Promise((resolve, reject) => { setTimeout(() => { console.log('async2'); resolve('async2完成') }, 2000); }) } function async3 () { return new Promise((resolve, reject) => { setTimeout(() => { console.log('async3'); resolve('async3完成') }, 3000); }) } Promise.all([async1(), async2(), async3()]).then((result) => { console.log(result); // do something... }).catch((err) => { console.log(err); }); // result: async1 async2 async3 [ 'async1完成', 'async2完成', 'async3完成' ]
該方法適用於遊戲類一些場景,全部素材、靜態資源請求都加載完成,在進行頁面的初始化promise
race也提供了並行的操做能力,和all方法相反,大白話就是:all是以函數中執行最慢的那一個爲準,race是以函數中執行最快的那一個爲準。race接收一個數組參數,它會把執行最快的那個異步操做的結果傳給then。app
// 以上面的三個異步操做函數爲例 Promise.race([async1(), async2(), async3()]).then((result) => { console.log(result); }).catch((err) => { console.log(err); }); // result: async1 async1完成 async2 async3
該方法適用於請求超時的場景,好比請求圖片資源,超過5秒就reject操做。dom
function requestImg() { return new Promise((resolve, reject) => { setTimeout(() => { resolve('請求圖片資源') }, 6000); }) } function timeout() { return new Promise((resolve, reject) => { setTimeout(() => { reject('請求超時'); }, 3000); }) } Promise.race([requestImg(), timeout()]).then((result) => { console.log(result); }).catch((err) => { console.log(err); }); // result: 請求超時 上面在請求超時完成後,其實requestImg()函數並無中止執行,而是不會再進入resolve的回調函數中了。
Set做爲ES6新的數據解構(類數組),它的成員都是惟一的,由於最直接的使用場景即是去重、並、差、交集的使用。它使用的算法叫作「Same-value-zero equality」,相似精確運算的===,主要是NaN,這裏它將兩個視爲相等。參見:http://es6.ruanyifeng.com/#docs/set-map#Set
// Set實例的經常使用方法和屬性add,delete,clear,has、size const s = new Set(['A', 'B', 'C']); console.log(s); // Set { 'A', 'B', 'C' } console.log(s.has('A')) // true,bool值 console.log(s.size) // 3 console.log(s.clear()) // Set {} console.log(s.delete('A')) // true,bool值 同時Set實例配合經常使用遍歷方法,實現並、交、差集。 const a =[1, 2, 3] const b = [2, 3, 4]; // 並集 const s = Array.from(new Set([...a, ...b])); // [ 1, 2, 3, 4 ] // 交集、差集 const bSet = new Set(b); const interestSet = a.filter(v => bSet.has(v)); // [ 2, 3 ] const interestSet = a.filter(v => !bSet.has(v)); // [ 1 ]
ES7在ES6的基礎上添加三項內容:求冪運算符(**)、Array.prototype.includes()方法、函數做用域中嚴格模式的變動。
求冪運算符(**),這是一箇中綴例子,效仿自Ruby等語法,使用更簡潔
Math.pow(3, 2) === 3 ** 2 // 9 Array.prototype.includes()
數組原型的方法,查找一個數值是否在數組中,只能判斷一些簡單類型的數據,對於複雜類型的數據沒法判斷。該方法接受兩個參數,分別是查詢的數據和初始的查詢索引值。
[1, 2, 3].indexOf(3) > -1 // true 等同於: [1, 2, 3].includes(3) // true
includes方法略勝一籌,直接返回bool。indexOf須要返回數組下標,咱們須要對下標值在進行操做,進而判斷是否在數組中。
二者這都是經過===進行數據處理,可是對NaN數值的處理行爲不一樣。includes對NaN的處理不會遵循嚴格模式去處理,因此返回true。indexOf會按照嚴格模式去處理,返回-1。
[1, 2, NaN].includes(NaN) // true [1, 2, NaN].indexOf(NaN) // -1
若是僅僅查找數據是否在數組中,建議使用includes,若是是查找數據的索引位置,建議使用indexOf更好一些
async、await異步解決方案 提出場景有兩個:JS是單線程、優化回調地獄的寫法。
this.$http.jsonp('/login', (res) => { this.$http.jsonp('/getInfo', (info) => { // do something }) }) })
在ES6中爲了解決回調的書寫方式,引入了Promise的then函數,業務邏輯不少的時候,須要鏈式多個then函數,語義會變得很不清楚。
new Promise((resolve, reject) => {this.login(resolve)}) .then(() => this.getInfo()) .then(() => {// do something}) .catch(() => { console.log("Error") })
Generator函數應運而生,它只是一個分段執行任務,經過狀態指針next分佈執行任務,可是流程管理不太方便(每一個階段什麼時候執行不太明瞭),因此它只是一箇中間產物。
const gen = function* () { const f1 = yield this.login() const f2 = yield this.getInfo() };
ES8中把async和await變得更加方便,它其實就是Generator的語法糖。async/await是寫異步代碼的新方式,之前的方法有回調函數和Promise。相比於Promise,它更加簡潔,而且處理錯誤、條件語句、獲取中間值都更加方便。
async function asyncFunc(params) { const result1 = await this.login() const result2 = await this.getInfo() }
若是想進一步瞭解async的具體時間,能夠參見阮一峯的博客es6.ruanyifeng.com/#docs/async
Object.entries()
該方法會將某個對象的可枚舉屬性與值按照二維數組的方式返回。(若是目標對象是數組,則會將數組的下標做爲鍵值返回)
Object.values({one: 1, two: 2}) // [1, 2] Object.values({3: 'a', 1: 'b', 2: 'c'}) // ['b', 'c', 'a'] Object.extries([1, 3]) //[1, 3]
ES8提供了新的字符串填充方法,該方法可使得字符串達到固定長度。它有兩個參數,字符串目標長度和填充內容。
'react'.padStart(10, 'm') //'mmmmmreact' 'react'.padEnd(10, 'm') //' reactmmmmm' 'react'.padStart(3, 'm') // 'vue'