Reputation: 19097
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
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