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
廣告