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