如何在 JavaScript 中使用 Rest、預設和解構引數對引數物件進行引數化?


預設

這有助於輕鬆處理函式引數。輕鬆設定預設引數,允許使用預設值初始化形式引數。只有在沒有傳入值或值未定義時才可能做到這一點。讓我們看一個示例:

示例

線上演示

<html>
   <body>
      <script>
         // default is set to 1
         function inc(val1, inc = 1) {
            return val1 + inc;
         }
         document.write(inc(10,10));
         document.write("<br>");
         document.write(inc(10));
      </script>
   </body>
</html>

rest

ES6 引入 rest 引數,減輕開發者的工作量。對於引數物件,rest 引數用三個點(...)表示,並放在引數之前。

示例

讓我們看下面的程式碼段:-

<html>
   <body>
      <script>
         function addition(…numbers) {
            var res = 0;
            numbers.forEach(function (number) {
               res += number;
            });
            return res;
         }
         document.write(addition(3));
         document.write(addition(5,6,7,8,9));
      </script>
   </body>
</html>

解構

ES6 中引入的引數用於與模式匹配繫結。如果未找到該值,則返回 undefined。讓我們看看 ES6 如何允許將陣列解構為單獨的變數

示例

線上演示

<html>
   <body>
      <script>
         let marks = [92, 95, 85];
         let [val1, val2, val3] = marks;

         document.write("Value 1: "+val1);
         document.write("<br>Value 2: "+val2);
         document.write("<br>Value 3: "+val3);
      </script>
   </body>
</html>

更新於: 2020 年 6 月 15 日

110 次瀏覽

開啟你的 職業生涯

完成課程取得認證

開始
廣告