ES8 新特性



本章重點介紹 ES8 的新特性。

字串填充

ES8 引入了兩個字串處理函式用於填充字串。這些函式可用於在字串值的開頭和結尾新增空格或任何所需的字元集。

String.padStart()

此函式使用給定的輸入字串從開頭重複填充當前字串,直到當前字串達到給定的長度。padStart() 函式的語法如下:

語法

string_value.padStart(targetLength [, padString])

padStart() 函式接受兩個引數,如下所示:

  • targetLength - 一個數值,表示填充後字串的目標長度。如果此引數的值小於或等於字串的現有長度,則按原樣返回字串值。

  • padString - 這是一個可選引數。此引數指定應用於填充字串的字元。如果未向此引數傳遞值,則字串值將用空格填充。

示例

以下示例宣告一個字串變數 product_cost。該變數將從左側用零填充,直到字串的總長度為七。該示例還說明了如果未向第二個引數傳遞值,padStart() 函式的行為。

<script>

   //pad the String with 0
   let product_cost = '1699'.padStart(7,0)
   console.log(product_cost)
   console.log(product_cost.length)

   //pad the String with blank spaces
   let product_cost1 = '1699'.padStart(7)
   console.log(product_cost1)
   console.log(product_cost1.length)
</script>

以上程式碼的輸出如下:

0001699
7
1699
7

String.padEnd()

此函式使用給定的輸入字串從結尾重複填充當前字串,直到當前字串達到指定的長度。

padEnd() 函式的語法如下:

語法

string_value.padEnd(targetLength [, padString])

padEnd() 函式接受兩個引數:

  • targetLength - 一個數值,表示填充後字串的目標長度。如果此引數的值小於或等於字串的現有長度,則按原樣返回字串值。

  • padString - 這是一個可選引數。此引數指定應用於填充字串的字元。如果未向此引數傳遞值,則字串值將用空格填充。

示例

以下示例宣告一個字串變數 product_cost。該變數將從右側用零填充,直到字串的總長度為七。該示例還說明了如果未向第二個引數傳遞值,padStart() 函式的行為。

<script>

   //pad the string with x
   let product_cost = '1699'.padEnd(7,'x')
   console.log(product_cost)
   console.log(product_cost.length)
   
   //pad the string with spaces
   let product_cost1 = '1699'.padEnd(7)
   console.log(product_cost1)
   console.log(product_cost1.length)
</script>

以上程式碼的輸出如下:

1699xxx
7
1699
7

尾隨逗號

尾隨逗號只是列表中最後一項後面的逗號。尾隨逗號也稱為最終逗號。

尾隨逗號和陣列

使用 Array.prototype.forEach 迴圈時,會跳過陣列中的尾隨逗號。

示例

以下示例使用 foreach 迴圈迭代帶有尾隨逗號的陣列。

<script>

   let marks = [100,90,80,,]
   console.log(marks.length)
   console.log(marks)
   marks.forEach(function(e){ //ignores empty value in array
      console.log(e)
   })
</script>

以上程式碼的輸出如下:

4
[100, 90, 80, empty]
100
90
80

尾隨逗號和函式呼叫

在定義或呼叫函式時,作為引數傳遞的尾隨逗號會被 JavaScript 執行時引擎忽略。但是,有兩個例外:

  • 僅包含逗號的函式定義或呼叫將導致 SyntaxError。例如,以下程式碼段將丟擲錯誤:

function test(,){} // SyntaxError: missing formal parameter
(,)=>{}; //SyntaxError: expected expression, got ','
test(,) //SyntaxError: expected expression, got ','
  • 尾隨逗號不能與 rest 引數一起使用。

function test(...arg1,){} // SyntaxError: parameter after rest parameter
(...arg1,)=>{} // SyntaxError: expected closing parenthesis, got ','

示例

以下示例宣告一個在引數列表中帶有尾隨逗號的函式。

<script>

   function sumOfMarks(marks,){ // trailing commas are ignored
      let sum=0;
      marks.forEach(function(e){
         sum+=e;
      })
      return sum;
   }

   console.log(sumOfMarks([10,20,30]))
   console.log(sumOfMarks([1,2,3],))// trailing comma is ignored
</script>

以上程式碼的輸出如下:

60
6

Object.entries() 和 Object.values()

ES8 向內建 Object 型別引入了以下新方法:

  • Object.entries - Object.entries() 方法可用於訪問物件的全部屬性。

  • Object.values() - Object.values() 方法可用於訪問物件的全部屬性的值。

  • Object.getOwnPropertyDescriptors() - 此方法返回一個物件,其中包含物件的全部自有屬性描述符。如果物件沒有任何屬性,則可能會返回一個空物件。

示例

<script>
   const student ={
      firstName:'Kannan',
      lastName:'Sudhakaran'
   }
   console.log(Object.entries(student))
   console.log(Object.values(student))
</script>

以上程式碼的輸出如下:

[
["firstName", "Kannan"],
["lastName", "Sudhakaran"],
]
["Kannan", "Sudhakaran"]

示例

<script>
   const marks = [10,20,30,40]
   console.log(Object.entries(marks))
   console.log(Object.values(marks))
</script>

以上程式碼的輸出如下:

["0", 10],
["1", 20],
["2", 30],
["3", 40]
]
[10, 20, 30, 40]

示例

<script>
   const student = {
      firstName : 'Mohtashim',
      lastName: 'Mohammad',
      get fullName(){
         return this.firstName + ':'+ this.lastName
      }
   }
   console.log(Object.getOwnPropertyDescriptors(student))
</script>

以上程式碼的輸出如下:

{firstName: {value: "Mohtashim", writable: true, enumerable: true, configurable: true}
fullName: {get: ƒ, set: undefined, enumerable: true, configurable: true}
lastName: {value: "Mohammad", writable: true, enumerable: true, configurable: true}
}

Async 和 Await

Async/Await 是 ES8 中一個非常重要的特性。它是 JavaScript 中 Promise 的語法糖。await 關鍵字與 promise 一起使用。此關鍵字可用於暫停函式的執行,直到 promise 完成。如果 promise 已完成,則 await 關鍵字返回 promise 的值;如果 promise 已拒絕,則丟擲錯誤。await 函式只能在標記為 async 的函式內使用。使用 async 關鍵字宣告的函式始終返回一個 promise。

語法

帶有 await 的 async 函式的語法如下:

async function function_name(){
   let result_of_functionCall = await longRunningMethod();
}
//invoking async function

function_name().then(()=>{})
   .catch(()=>{})

考慮一個示例,該示例具有一個非同步函式,該函式需要兩秒鐘才能執行並返回一個字串值。該函式可以透過兩種方式呼叫,如下所示

  • 使用 promise.then()
  • 使用 async/await。

以下程式碼顯示了使用傳統的 ES6 語法(promise.then())呼叫非同步函式。

<script>
   function fnTimeConsumingWork(){
      return new Promise((resolve,reject)=>{
         setTimeout(() => {
            resolve('response is:2 seconds have passed')
         }, 2000);
      })
   }

   fnTimeConsumingWork().then(resp=>{
      console.log(resp)
   })
   console.log('end of script')
</script>

以上程式碼的輸出如下:

end of script
response is:2 seconds have passed

以下程式碼顯示了使用 ES8 語法(async/await)呼叫非同步函式的更簡潔的方法。

<script>
   function fnTimeConsumingWork(){
      return new Promise((resolve,reject)=>{
         setTimeout(() => {
            resolve('response is:2 seconds have passed')
         }, 2000);
      })
   }
   async function my_AsyncFunc(){
      console.log('inside my_AsyncFunc')
      const response = await fnTimeConsumingWork();// clean and readable
      console.log(response)
   }
   my_AsyncFunc();
   console.log("end of script")
</script>

以上程式碼的輸出如下:

inside my_AsyncFunc
end of script
response is:2 seconds have passed

使用 Async/await 的 Promise 鏈

以下示例使用 async/await 語法實現 Promise 鏈。

在此示例中,add_positivenos_async() 函式非同步新增兩個數字,如果傳遞負值則拒絕。當前非同步函式呼叫的結果作為引數傳遞給後續的函式呼叫。

<script>
   function add_positivenos_async(n1, n2) {
      let p = new Promise(function (resolve, reject) {
         if (n1 >= 0 && n2 >= 0) {
            //do some complex time consuming work
            resolve(n1 + n2)
         } else
            reject('NOT_Postive_Number_Passed')
      })
      return p;
   }
   async function addInSequence() {
      let r1 = await add_positivenos_async(10, 20)
      console.log("first result", r1);
      let r2 = await add_positivenos_async(r1, r1);
      console.log("second result", r2)
      let r3 = await add_positivenos_async(r2, r2);
      console.log("third result", r3)
      return "Done Sequence"
   }
   addInSequence().then((r)=>console.log("Async :",r));
   console.log('end')
</script>

以上程式碼的輸出如下:

end
first result 30
second result 60
third result 120
Async : Done Sequence
廣告
© . All rights reserved.