将未知数量的参数传递给javascript函数 [英] Pass unknown number of arguments into javascript function
问题描述
有没有办法传递未知数量的参数,如:
Is there a way to pass an unknown number of arguments like:
var print_names = function(names) {
foreach(name in names) console.log(name); // something like this
}
print_names('foo', 'bar', 'baz');
另外,我如何获得传入的参数数量?
Also, how do I get the number of arguments passed in?
推荐答案
ES3(或ES5或oldschool Javascript)
您可以访问传递给任何javascript函数的参数通过神奇的参数
对象,其行为与数组类似。使用参数
你的函数看起来像
ES3 (or ES5 or oldschool Javascript)
You can access the arguments passed to any javascript function via the magic arguments
object, which behaves similarly to an array. Using arguments
your function would look like
var print_names = function() {
for (var i=0; i<arguments.length; i++) console.log(arguments[i]);
}
重要的是要注意参数
不一个数组。 MDC有一些很好的文档: https://developer.mozilla.org/en /Core_JavaScript_1.5_Guide/Functions#Using_the_arguments_object
It's important to note that arguments
is not an array. MDC has some good documentation on it: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#Using_the_arguments_object
如果要将参数
转换为数组,您可以执行以下操作: .slice()
, .push()
等,使用以下内容:
If you want to turn arguments
into an array so that you can do things like .slice()
, .push()
etc, use something like this:
var args = Array.prototype.slice.call(arguments);
ES6 / Typescript
有一个更好的办法!新的其他参数功能让您有所了解:
ES6 / Typescript
There's a better way! The new rest parameters feature has your back:
var print_names = function(...names) {
for (let i=0; i<names.length; i++) console.log(names[i]);
}
这篇关于将未知数量的参数传递给javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!