chanjianyi
chanjianyi

Reputation: 615

How to pass parameter to the function with apply in javascript?

I have functions, to pass the parameters from a to b.

but it seems the apply just access 2 parameters

function a(){
  var p1=1;
  var p2=2;
  b.apply(this,arguments);
}


function b(){
    //so how to get p1,p2 in this function?
    console.log(arguments);
}

a(3,4);

so how to pass the p1 p2 in function a and get 1,2,3,4 in functionb?

Upvotes: 0

Views: 179

Answers (3)

Ivneet singh wahi
Ivneet singh wahi

Reputation: 1

Try this code.

void temp() { 
    var animals = ["cat", "dog", "horse", "cow"];
    animals.forEach(function (eachName, index) {
     console.log(index + 1 + ". " + eachName); 
    });
}

Upvotes: -1

Artur Smirnov
Artur Smirnov

Reputation: 804

In order to pass your variables to another function you have to add them to the array you provide to apply. But you can not add them directly to the arguments variable since it's not the real array. So first of all you have to build a new array which you would pass to apply. You can transform arguments to array by var newArray = Array.prototype.slice.call(arguments); - this creates new array from arguments. Now you can act with it as with regular array (newArray.push(p1); or newArray = newArray.concat([p1, p2]); and so on). And then just pass this array to apply instead of arguments.

So your code would change this way:

function a(){
  var p1=1;
  var p2=2;
  var argumentsArray = Array.prototype.slice.call(arguments);
  b.apply(this, argumentsArray.concat([p1, p2]));
}


function b(){
    console.log(arguments);
}

a(3,4); // output: [3, 4, 1, 2];

If you need to prepend p1 and p2 you can use unshift

Upvotes: 1

zerkms
zerkms

Reputation: 254906

You create an array with all the parameters you need to pass:

var combinedArray = [p1, p2].concat(Array.prototype.slice.call(arguments));

this function:

  1. Creates an array with first 2 elements as p1 and p2
  2. And appends the arguments array to it.

Then you can call it as b.apply(this, combinedArray)

PS:

The Array.prototype.slice.call(arguments) is used to convert arguments object to a real array.

Upvotes: 4

Related Questions