ES7 ES8 的新特性(部分)

186 阅读1分钟

ES7 只有两个新特性

  • includes():在之前,验证数组中是否存在某个元素,只能应indexOf来实现,但是现在我们可以使用ES7的新特性includes()来实现
let arr = ['react', 'angular', 'vue'];

if (arr.includes('react'))

{

console.log('react存在');

}

  • 指数操作符:使用自定义的递归函数calculateExponent或者Math.pow()进行指数运算,用了ES7就可以直接用指数运算符了(**)
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);    


执行的就是7的三次方(Math.pow(7,3))

ES8的新特性

  • 遍历对象的属性值
let obj = {a: 1, b: 2, c: 3}

Object.keys(obj).forEach((key) =>

{

console.log(obj[key]); // 输出1, 2, 3

});
  • 遍历对象的属性名和属性值
let obj = {a: 1, b: 2, c: 3};

Object.entries(obj).forEach(([key, value]) =>

{

console.log(key + ": " + value); // 输出a: 1, b: 2, c: 3

})
  • 对象变数组(解析后台返回的数据时候常用)
Object.values({w:2,f:5})
// [2, 5]
  • 使用Object.entries():遍历对象的属性名和属性值:
let obj = {a: 1, b: 2, c: 3}; 
Object.entries(obj).forEach(([key, value]) =>{   
 console.log(key + ": " + value); // 输出a: 1, b: 2, c: 3
})

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