ES7 - 新特性



本章介绍了 ES7 中的新特性。

指数运算符

ES7 引入了一种新的数学运算符,称为指数运算符。此运算符类似于使用 Math.pow() 方法。指数运算符由双星号 ** 表示。此运算符只能用于数值。使用指数运算符的语法如下所示:

语法

指数运算符的语法如下所示:

base_value ** exponent_value

示例

以下示例使用Math.pow()方法和指数运算符计算数字的指数。

<script>
   let base = 2
   let exponent = 3
   console.log('using Math.pow()',Math.pow(base,exponent))
   console.log('using exponentiation operator',base**exponent)
</script>

以上代码片段的输出如下所示:

using Math.pow() 8
using exponentiation operator 8

数组 includes

ES7 中引入的 Array.includes() 方法用于检查数组中是否存在某个元素。在 ES7 之前,可以使用 Array 类的 indexof() 方法来验证数组中是否存在某个值。如果找到数据,则 indexof() 返回数组中该元素第一次出现的索引;否则,如果数据不存在,则返回 -1。

Array.includes() 方法接受一个参数,检查作为参数传递的值是否存在于数组中。如果找到该值,则此方法返回 true;否则,如果该值不存在,则返回 false。使用 Array.includes() 方法的语法如下所示:

语法

Array.includes(value)

Array.includes(value,start_index)

第二个语法检查从指定的索引开始是否存在该值。

示例

以下示例声明一个数组 marks 并使用 Array.includes() 方法来验证数组中是否存在某个值。

<script>
   let marks = [50,60,70,80]
   //check if 50 is included in array
   if(marks.includes(50)){
      console.log('found element in array')
   }else{
      console.log('could not find element')
   }

   // check if 50 is found from index 1
   if(marks.includes(50,1)){ //search from index 1
      console.log('found element in array')
   }else{
      console.log('could not find element')
   }

   //check Not a Number(NaN) in an array
   console.log([NaN].includes(NaN))

   //create an object array
   let user1 = {name:'kannan'},
   user2 = {name:'varun'},
   user3={name:'prijin'}
   let users = [user1,user2]

   //check object is available in array
   console.log(users.includes(user1))
   console.log(users.includes(user3))
</script>

以上代码的输出将如下所示:

found element in array
could not find element
true
true
false
广告