ES7和ES8的筆記
阿新 • • 發佈:2019-01-28
ES7的特性比ES6的特性多了兩個
1.Array.prototype.includes
2.Exponentiation Operator(求冪運算)
ES8新增提案:
1.Object.values / Object.entries
2.String padding(字串填充)
3.Object.getOwnPropertyDescriptors
4.函式引數列表和呼叫中的尾逗號(Trailing commas)
5.非同步函式(Async Functions)
詳細解釋:
1.Array.prototype.includes
Array.prototype.includes替代indexOf方法用來檢測陣列中是否存在這個值,
利用indexOf判斷是否陣列存在值,是根據返回一個元素在陣列中的位置或者
-1當這樣的元素不能被找到的情況下,返回的是一個數字,而不是一個布林值。
let arr = [‘react’, ‘angular’, ‘vue’]
// WRONG if (arr.indexOf('react')) { // 0 -> evaluates to false, definitely as we expected console.log('Can use React') // this line would never be executed } // Correct if (arr.indexOf('react') !== -1) { console.log('Can use React') } 或者使用一點點hack 位運算子 ~ 使程式碼更加緊湊一些,因為~(位異或)對任何數字相當於-(a + 1): let arr = ['react', 'angular', 'vue'] // Correct if (~arr.indexOf('react')) { console.log('Can use React') } 等同於ES7中使用includes程式碼 let arr = ['react', 'angular', 'vue'] // Correct if (arr.includes('react')) { console.log('Can use React') } includes還可以運用到字串中 eg: let str = 'React Quickly' // Correct if (str.toLowerCase().includes('react')) { // true console.log('Found "react"') }
includes直接返回的是布林值,不是一個數值
擴充套件:includes可以有兩個引數
includes(a,fromIndex)// a:檢測是否存在的值,fromIndex:
從特定的索引值進行匹配
console.log([‘a’, ‘b’, ‘c’].includes(‘a’, 1)) // === false)
2.Exponentiation Operator(求冪運算) Es6中,Math.pow可以建立一個短的遞迴箭頭函式 calculateExponent = (base, exponent) => base*((--exponent>1)?calculateExponent(base, exponent):base) console.log(calculateExponent(7,12) === Math.pow(7,12)) // true console.log(calculateExponent(2,7) === Math.pow(2,7)) // true es7中,以數字嚮導的開發者可以使用更短的語法 let a = 7 ** 12 let b = 2 ** 7 console.log(a === Math.pow(7,12)) // true console.log(b === Math.pow(2,7)) // true 2.String padding(字串填充) console.log('react'.padStart(10).length) // " react" is 10 console.log('backbone'.padStart(10).length) // " backbone" is 10 預設填充的字元是空格鍵 console.log('react'.padStart(10, '_')) // "_____react" console.log('backbone'.padStart(10, '*')) // "**backbone" 3.非同步函式(或者async/await)特性操作是Promise最重要的功能 axios.get(`/q?query=${query}`) .then(response => response.data) .then(data => { this.props.processfetchedData(data) // Defined somewhere else }) .catch(error => console.log(error))