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))