Nick Vanderbilt
Nick Vanderbilt

Reputation: 38450

JavaScript how to pass arguments

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.

Upvotes: 1

Views: 235

Answers (6)

sth
sth

Reputation: 229593

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.

Upvotes: 7

Powerlord
Powerlord

Reputation: 88796

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); 

Upvotes: 0

Gerardo Abdo
Gerardo Abdo

Reputation: 1200

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>

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415800

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.

Upvotes: 0

instanceof me
instanceof me

Reputation: 39138

For this precise situation:

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

For any number of arguments, see sth's answer

Upvotes: 0

Ricky
Ricky

Reputation: 5377

Why not just do:

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

?

Upvotes: -1

Related Questions