0

I would like to call a function, lets say test_func that accepts variable number of arguments. (like this function http://locutus.io/php/array/array_intersect_assoc/)

Please note I would like to avoid modifying the receiver function! All the answers so far require modifying the receiver function, just as the linked "possible dupes". I would like to programmatically generate the argument list itself. (eg pass variable number of objects)

I do not know in advance how many arguments I will have. How can I generate a variable length argument with objects?

var v1 = {test:1};
var v2 = {test2:2};
var obj_arr = [v1,v2];
console.log(test_func (obj_arr.join(",")));

//in my case this should be the equivalent of test_func (v1,v2);

function test_func (object_arg) {
  return(arguments.length);
  }
//should return 2!
giorgio79
  • 3,787
  • 9
  • 53
  • 85
  • Please note I want to avoid modifying the receiver function! All the answers so far require modifying the receiver function, and the linked possible dupes. – giorgio79 Sep 04 '17 at 05:32
  • console.log( obj_arr.length ); will give its length, is this what you want ?? – Ananthakrishnan Baji Sep 04 '17 at 05:33
  • 1
    @giorgio79 in that case, only option is to merge all arguments in an array/object manually and pass it – Rajesh Sep 04 '17 at 05:34
  • Thx @Rajesh , so I will need to modify the receiver function http://locutus.io/php/array/array_intersect_assoc/ . There is no way to programmatically generate the argument list of objects? – giorgio79 Sep 04 '17 at 05:35
  • To be honest, that function should work with `n` number of arguments without any issue as it **is** using `arguments`. What exactly is the issue? – Rajesh Sep 04 '17 at 05:37
  • How do I generate the argument list? This does not work `test_func (obj_arr.join(","))` – giorgio79 Sep 04 '17 at 05:38
  • `.join` will return a string and not object. And honestly, that function is confusing me a bit. Probably someone who has used it might be able to help you. – Rajesh Sep 04 '17 at 05:41

1 Answers1

0

If you're in an ES5 environment you can use arguments:

function test() {
    var param1 = arguments[0];
    var param2 = arguments[1];
    // arguments is array like, you can iterate over it with a loop
}

If you are in an ES6 environment you can either use the rest operator as suggested by Suren or also use the arguments variant as above - depending on the convention of you're team.

Severin
  • 308
  • 1
  • 11