Reputation: 13367
/*
* Example function for operating with dynamic arguments
*/
function something(){
for(var i in arguments){
arguments[i] = arguments[i] + Math.random() * 25;
}
return arguments;
}
There are no errors, have not noticed performance drops, and, the values are changed.
So, is it safe to do such operations on dynamic arguments?
Upvotes: 0
Views: 31
Reputation: 664599
Yes, it is safe. Yet, you should beware of the functionality of the arguments
object, which differs between Ecmascript implementations and versions. It can be a pseudo-array linked absolutely to the argument variables, but also can be a independent Array instance.
If you know your environment it's OK, elsewhile it's better to code
function something() {
var l = arguments.length,
res = new Array(l);
for(var i=0; i<l; i++) {
res[i] = arguments[i] + Math.random() * 25;
}
return res;
}
Upvotes: 0
Reputation: 119847
arguments
is a "pseudo-array". How would it be different from returning an array? The only downside is that arguments
is not an array and therefore, you don't have the array properties and methods you need.
Upvotes: 0
Reputation: 318518
I would never return it since it's not a real array (see http://javascriptweblog.wordpress.com/2011/01/18/javascripts-arguments-object-and-beyond/ for some information about special behaviour of that object) - so depending on what the calling code does with it, it would fail.
However, you can easily turn it into an array:
var args = Array.prototype.slice.call(arguments);
I would not modify the original object since changes also change the corresponding named arguments in case your function accepts any.
Upvotes: 3