Stealth
Stealth

Reputation: 155

Call a function multiple times with more than one argument in JavaScript

Let's say I have this function

function myFunction(a, b, c) {
    ... code here ...
}

Now I want to call it multiple times with several different arguments each time:

myFunction('sky', 'blue', 'air');
myFunction('tree', 'green', 'leaf');
myFunction('sun', 'yellow', 'light');
myFunction('fire', 'orange', 'heat');
myFunction('night', 'black', 'cold');

How can I merge all those calls in just one?

I know how to do it with iterations or forEach when there is just one argument, but I can't figure out how to do it with various non-numerical arguments.

Upvotes: 1

Views: 5888

Answers (3)

SantiG
SantiG

Reputation: 828

lets suppose you already have an array with all the values:

var colors = ['sky', 'blue', 'air', 'tree', 'green', 'leaf', 'sun', 'yellow', 'light', 'fire', 'orange', 'heat', 'night', 'black', 'cold'];

while(colors.length > 0){
  myFunction.apply(this, colors.splice(0,3)); //call the function with chunks of 3 elements
}

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074684

Unless you change myFunction, you can't call it once and have it magically act as though it had been called five times.

You can code a single call in a loop, though, if the information you're for the arguments using is stored elsewhere.

For instance, if we assume an array of objets:

var data = [
    {a: 'sky', b: 'blue', c: 'air'},
    {a: 'tree', b: 'green', c: 'leaf'},
    {a: 'sun', b: 'yellow', c: 'light'},
    {a: 'fire', b: 'orange', c: 'heat'},
    {a: 'night', b: 'black', c: 'cold'}
]:

then

data.forEach(function(entry) {
    myFunction(entry.a, entry.b, entry.c);
});

Or if it's an array of arrays, we can use the nifty Function#apply function:

var data = [
    ['sky', 'blue', 'air'],
    ['tree', 'green', 'leaf'],
    ['sun', 'yellow', 'light'],
    ['fire', 'orange', 'heat'],
    ['night', 'black', 'cold']
]:

then:

data.forEach(function(entry) {
    myFunction.apply(null, entry);
});

Upvotes: 5

Bergi
Bergi

Reputation: 664777

You seem to be looking for apply

var values = [
    ['sky', 'blue', 'air'],
    ['tree', 'green', 'leaf'],
    ['sun', 'yellow', 'light'],
    ['fire', 'orange', 'heat'],
    ['night', 'black', 'cold']
];
values.forEach(function(args) { myFunction.apply(null, args); })

or spread syntax in ES6:

for (const args of values) myFunction(...args);

Upvotes: 2

Related Questions