Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
912 views
in Technique[技术] by (71.8m points)

arrays - Unlimited arguments in a JavaScript function

Can a JavaScript function take unlimited arguments? Something like this:

testArray(1, 2, 3, 4, 5...);

I am trying:

var arr = [];
function testArray(A) {
    arr.push(A);
}

But this doesn't work (output is only the first argument). Or the only way is:

function testArray(a, b, c, d, e...) {

}

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's a weird "magic" variable you can reference called "arguments":

function manyArgs() {
  for (var i = 0; i < arguments.length; ++i)
    alert(arguments[i]);
}

It's like an array, but it's not an array. In fact it's so weird that you really shouldn't use it much at all. A common practice is to get the values of it into a real array:

function foo() {
  var args = Array.prototype.slice.call(arguments, 0);
  // ...

In that example, "args" would be a normal array, without any of the weirdness. There are all sorts of nasty problems with "arguments", and in ECMAScript 5 its functionality will be curtailed.

edit — though using the .slice() function sure is convenient, it turns out that passing the arguments object out of a function causes headaches for optimization, so much so that functions that do it may not get optimized at all. The simple, straightforward way to turn arguments into an array is therefore

function foo() {
  var args = [];
  for (var i = 0; i < arguments.length; ++i) args[i] = arguments[i];
  // ...
}

More about arguments and optimization.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...