JavaScript 函数中的默认参数和其余参数有哪些不同?


默认参数

默认参数轻松处理函数参数。你可以轻松设置默认参数,允许使用默认值初始化形式化参数。在未传递值或未定义值时,才可行。 

示例

 实时演示

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

输出

其余参数

ES6 带来了其余参数,减轻了开发人员的工作。对于 arguments 对象,其余参数以三个点 … 标记,并且在参数之前。使用此方法,将无限数量的参数设置为数组,数组是 Array 实例。

示例

让我们看看以下代码片段 −

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

更新时间:2020-6-23

312 次浏览

开启你的 职业生涯

完成本课程即可获取认证

开始
广告
© . All rights reserved.