1
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.

1
  • I am learning JavaScript so the answer must be using arguments and not directly passing the values. Commented Feb 18, 2010 at 16:59

6 Answers 6

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I've been using JavaScript for a long time and only just heard of this. Why!!!?? +1
same here. i have used it for a long time but have never had a chance using this apply function. nice to know. and help me solve some problems. thanks.
0

For this precise situation:

function f2(i1,i2){ f1(i1, i2); }

For any number of arguments, see sth's answer

Comments

0

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

The whole purpose of using arguments is so that the number of params can be variable.
0

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

0

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

-1

Why not just do:

function f2(i1,i2){ f1(i1,i2); }

?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.