javascript无限请求_Javascript:“无限”函数参数?

In Chrome, when I type console.log in the one below:

console.log("A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter");

...it prints it correctly, with no errors or warnings. I appended more parameters, but it still prints it out correctly.

console.log("A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter", "A parameter");

How can I have an "infinite" parameter function just like that one?

解决方案

Functions can access an array-like object called arguments that contains all the arguments that they received

function print_my_arguments(/**/){

var args = arguments;

for(var i=0; i

console.log(args[i]);

}

};

And you can do the opposite conversion (call a function given a list of arguments) with the apply method:

// These are equivalent:

print_my_arguments(1,2,3);

print_my_arguments.apply(null, [1,2,3]);

// The first parameter to `apply` is the `this`.

// It is used when the function is a method.

foo.bar(1,2,3);

var f = foo.bar; f.apply(foo, [1,2,3]);

Some important points to note:

arguments isn't an actual array and it has none of the usual array methods (slice, join, etc). You can convert it to an array with the following line:

var args = Array.prototype.slice.call(arguments);

Slice is also useful if you want your array to only contain the non-named arguments that were received:

function foo(first_arg, second_arg /**/){

var variadic_args = Array.prototype.slice.call(arguments, 2);

}

Not every browser can handle an arbitrarily large number of function parameters. Last time I tested this, in Chrome and IE there was a stackoverflow after some 200.000 arguments. If your function can receive an arbitrarily large number of arguments, consider packing all of those arguments in an regular array instead.

Those /**/ comments that appear in the arguments lists for my examples are not mandatory. They are just a coding a convention that I use to mark my variadic functions and differentiate them from regular functions.

// A quick glance would suggest that this function receives no

// parameters but actually it is a variadic function that gets

// its parameters via the `arguments` object.

function foo(){

console.log(arguments.length);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值