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

javascriptobject oriented programmingfront end technology

将数组作为函数参数传递

 过去,如果我们需要将数组作为函数参数传递,则应使用 apply()null 。使用 null 会使代码不干净。因此,为了使代码干净并将数组作为函数参数传递,spread 运算符应运而生。通过使用 spread 运算符,我们不需要使用 apply() 函数。让我们简要讨论一下。

示例

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

<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

相关文章