码迷,mamicode.com
首页 > 其他好文 > 详细

ES7与ES8新特性

时间:2018-10-24 20:17:06      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:验证   数组   timeout   字符串   操作符   let   ops   data   prototype   

以下记录几个可能经常用到的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)
})

 

ES7与ES8新特性

标签:验证   数组   timeout   字符串   操作符   let   ops   data   prototype   

原文地址:https://www.cnblogs.com/yinian/p/9844949.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!