Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Call function, pass array of arguments, similar to setTimout()'s functionality [duplicate]

Tags:

I want to do what setTimout does, manually, with no timeout.

setTimeout(function,0,args);

Just call a function and pass it an array of arguments, without knowing or caring how many arguments were there.

Basically I want to proxy the function call through another function.

I'm bad with terminology, sorry.

like image 780
somedev Avatar asked Dec 17 '09 19:12

somedev


People also ask

How do you pass an array as a function argument in JavaScript?

Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed.

How do you call a function with an array parameter?

Example: var fn = function() { console. log(arguments); } var args = [1,2,3]; fn(args); I need arguments to be [1,2,3] , just like my array.

Which keyword is used to access the array of arguments of a function in JavaScript?

You can access specific arguments by calling their index. var add = function (num1, num2) { // returns the value of `num1` console.


2 Answers

function f(a, b, c) { return a + b + c; }
alert(f.apply(f, ['hello', ' ', 'world']));
like image 140
just somebody Avatar answered Dec 02 '22 21:12

just somebody


In ES6:

function myFunc(a, b, c){
    console.log(a, b, c);
}

var args = [1, 2, 3];
myFunc(...args);
like image 38
Nainemom Avatar answered Dec 02 '22 20:12

Nainemom