ES7新特性(2016)

目录:

1.Array.prototype.includes()

2.指数操作符

概述:

ES2016添加了两个小的特性来说明标准化过程:

  1. 数组includes()方法,用来判断一个数组是否包含一个指定的值,如果包含,则返回true,否则返回false.
  2. a ** b指定运算符,它与Math.pow(a,b)相同。

1.Array.prototype.includes()

includes()函数用来判断一个数组是否包含一个指定的值,如果包含则返回true,否则返回false。

includes函数与indexOf函数很相似,下面两个表达式是等价的:

arr.includes(x)
arr.indexOf(x)
>= 0

例子:判断数组中是否包含某个元素:

  • 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存在')
}

2.指数操作符

在ES7中引入指数运算符 ** ,**与Math.pow(..)是等效的的计算结果。

例子:

  • 不使用指数运算符
//使用自定义的递归函数caculateExponent或者Math.pow()进行指数运算:
function caculateExponent(base,exponent){
     if(exponent === 1){
          return base;
     } else {
          return base * caculateExponent(base, exponent - 1);
     }
}
console.log(caculateExponent(2, 10));
console.log(Math.pow(2, 10));
  • 使用指数操作符
//使用指数运算符**,就像+,-等操作符一样
console.log(2**10)

 

posted @ 2021-05-17 09:02  小那  阅读(197)  评论(0编辑  收藏  举报