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


預設值

它能夠輕鬆處理函式引數。輕鬆設定預設值引數,允許使用預設值初始化形式引數。只有在沒有傳遞值或傳遞 undefined 的情況下才可能實現這一點。讓我們看一個示例

示例

動態演示

<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 引數,減輕了開發人員的工作。對於 arguments 物件,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>

更新於: 15-6 月-2020

110 次瀏覽

開啟你的職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.