ES7与ES8新特性

以下记录几个可能经常用到的es7与es8的新特性:

Array.prototype.includes()

不使用ES7

使用indexOf()验证数组中是否存在某个元素,这时需要根据返回值是否为-1来判断:

let arr = ['react', 'angular', 'vue'];
 
if (arr.indexOf('react') !== -1)
{
    console.log('React存在');
}
使用ES7

使用includes()验证数组中是否存在某个元素,更加直观简单:

let arr = ['react', 'angular', 'vue'];
 
if (arr.includes('react'))
{
    console.log('React存在');
}

includes方法同时也能用于字符串中验证是否存在某个元素

指数操作符

不使用ES7

使用自定义的递归函数calculateExponent或者Math.pow()进行指数运算:

function calculateExponent(base, exponent)
{
    if (exponent === 1)
    {
        return base;
    }
    else
    {
        return base * calculateExponent(base, exponent - 1);
    }
}
 
console.log(calculateExponent(7, 3)); // 输出343
console.log(Math.pow(7, 3)); // 输出343
使用ES7

使用指数运算符**,就像+、-等操作符一样:

console.log(7**3);

Async/Await

使用Promise

使用Promise写异步代码,会比较麻烦:

var run = function(){
  var _promise = new Promise(function(resolve, reject){
      setTimeout(function(){
          var rand = Math.random();
          if(rand<0.5){
              resolve("resolve" + rand);
          }else{
              reject("reject" + rand);
          }
      },1000);
  });
  return _promise;
}
run().then(function(data){
  console.log(data);
})
.catch(function(error){
  console.log(error)
});
使用Async/Await

Async/Await使得异步代码看起来像同步代码:

async fetchData(query) =>
{
    try
    {
        const response = await axios.get(`/q?query=${query}`);
        const data = response.data;
        return data;
    }
    catch (error)
    {
        console.log(error)
    }
}
 
fetchData(query).then(data =>
{
    this.props.processfetchedData(data)
})

 

转载于:https://www.cnblogs.com/yinian/p/9844949.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值