如何在 JavaScript 中将数组作为函数参数传递?


将数组作为函数参数传递

 过去,如果我们需要将数组作为函数参数传递,则需要使用apply()null 。使用 null 会使代码变得不简洁。为了使代码更简洁,并能够将数组作为函数参数传递,扩展运算符应运而生。通过使用扩展运算符,我们不再需要使用 apply() 函数。让我们简单地讨论一下。

示例

在下面的示例中,我们使用了 null apply() 来将数组作为函数参数传递。这是一种过时的方法。这种方法已被一种使用扩展运算符的现代方法取代。

在线演示

<html>
<body>
<script>
   function shareMar(a, b, c) {
      document.write(a);
      document.write("</br>");
      document.write(b);
      document.write("</br>");
      document.write(c);
   }
   var names = ['NSE', 'BSE', 'NIFTY'];
   shareMar.apply(null, names);
</script>
</body>
</html>

输出

NSE
BSE
NIFTY

如果我们观察下面的示例,apply() 函数和 null 没有被使用,取而代之的是使用了ES6 扩展运算符。使用扩展运算符使代码更优雅,并且不需要使用无用的 null 值。

示例

在线演示

<html>
<body>
<script>
   function shareMar(a, b, c) {
      document.write(a);
      document.write("</br>");
      document.write(b);
      document.write("</br>");
      document.write(c);
   }
   var names = ['NSE', 'BSE', 'NIFTY'];
   shareMar(...names);
</script>
</body>
</html>

输出

NSE
BSE
NIFTY

更新于: 2019-07-30

3K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.