如何在 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP