thdoan
thdoan

Reputation: 19097

How to dynamically construct a function's arguments without eval?

Given this code:

var arr = ['one', 'two'];
var obj = {
  func: function(a, b) {
    console.log(a, b);
  }
};

Is there a way to dynamically construct the function call passing the items in the array as arguments without using eval()? Basically, the equivalent of this:

eval('obj.func(' + arr.join(',') + ')');

Upvotes: 0

Views: 42

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370699

You can spread the array into the argument list:

var arr = ['one', 'two'];
var obj = {
  func: function(a, b) {
    console.log(a, b);
  }
};
obj.func(...arr);

Or, if the environment doesn't support spread, you can use apply, which allows you to call a function with the supplied array converted to parameters:

var arr = ['one', 'two'];
var obj = {
  func: function(a, b) {
    console.log(a, b);
  }
};
obj.func.apply(undefined, arr);

Upvotes: 2

Related Questions