function f1(i1, i2) {
log(i1);
log(i2);
}
function f2(i1,i2){
f1(arguments);
}
f2(100,200);
In the above case in function f1 i1 gets [100, 200] while i2 is undefined.
What is the correct way to pass arguments to f1 from f2.
-
I am learning JavaScript so the answer must be using arguments and not directly passing the values.Nick Vanderbilt– Nick Vanderbilt2010年02月18日 16:59:38 +00:00Commented Feb 18, 2010 at 16:59
6 Answers 6
Function objects have an apply() method:
f1.apply(null, arguments)
The first parameter passed is the object that should be this in the called function, the second parameter is an array containing the parameter values for the called function.
For this precise situation:
function f2(i1,i2){ f1(i1, i2); }
For any number of arguments, see sth's answer
Comments
If you must use the arguments object:
function f2(i1, i2) {
f1(arguments[0], arguments[1]);
}
I'm really wondering why you don't just pass i1 and i2 directly, but I'll give you the benefit of the doubt and assume for purposes of the question that this code is dramatically simpler than your real code.
1 Comment
arguments is so that the number of params can be variable.I do not understand your question, if you do this it will work:
<script>
function f1(i1, i2) { alert(i1+","+i2); log(i1); log(i2); }
function f2(i1,i2){ f1(i1,i2); }
f2(100,200);
</script>
Comments
f1 isn't returning any results. Even if it did, you'd need to return an array to return more than one value.
function f1(i1, i2) {
var returnArray = new Array();
var returnArray[0] = log(i1);
var returnArray[1] = log(i2);
return returnArray;
}
function f2(i1,i2) {
var results = f1(i1, i2);
}
f2(100,200);
Comments
Why not just do:
function f2(i1,i2){ f1(i1,i2); }
?