JavaScript 中“在預設引數後無預設值的引數”是什麼意思


預設引數的出現簡化了函式引數處理過程。預設引數允許使用預設值初始化形式引數。只有當未傳遞任何值或值為 undefined 時這才能實現。有了 ES6,你可以輕鬆設定預設引數。我們來看一個示例

示例

線上演示

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

以下程式碼可以正確執行,它展示了從左到右遍歷引數的工作原理。即使在後期新增無預設值的引數,它也會覆蓋預設引數。

示例

線上演示

<html>
   <body>
      <script>
         function display(val1 = 10, val2) {
            return [val1, val2];
         }
         document.write(display());
         document.write(display(20));
      </script>
   </body>
</html>

更新時間:6 月 16 日,2020

110 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始吧
廣告
© . All rights reserved.