ES7和ES8的笔记

1 篇文章 0 订阅

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

参考网址:https://www.jianshu.com/p/a138a525c287

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值