Vincent1989
Vincent1989

Reputation: 1657

Passing multiple/unknown number of variable(s) into JavasScript a parameter?

I'm creating a reusable function with multiple/unknown number of variable(s) and one callback.

//the number of variable will be dynamic
var a = "this is a.";
var b = "this is b.";

function callback(){
 console.log('callback successful');
}

//totalUp() will be reusable function
function totalUp(allVariables, callback){
 console.log('Here are the complete list: ' + allVariables + '.');
 callback();
}

//how do I pass unknown number of arguments(a and b) into one parameter?
totalUp({a,b},callback);

In my code above I'm passing a and b in form of object which doesn't work.

Upvotes: 0

Views: 95

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386680

I would change the sinature of the dunction and take first the necessary callback as first parameter and then take the dynamic arguments.

function upTo(cb, ...params) {
    cb(...params);
}

function cb(...params) {
    params.forEach(v => console.log(v));
}

upTo(cb, 1, 2, 3);

ES5

function upTo(cb) {
    cb.apply(null, Array.prototype.slice.call(arguments, 1));
}

function cb() {
    Array.prototype.slice.call(arguments).forEach(function (v) { console.log(v); });
}

upTo(cb, 1, 2, 3);

Upvotes: 0

TeaNyan
TeaNyan

Reputation: 5079

let allVars = [
    "this is a.",
    "this is b.",
]

You can have some more variables inserted into allVars and therefore you can have an unknown number of variables.

When you pass it to the function, you have 2 options.

First one is to pass array and to use it as array

function totalUp(allVars, callback){
  let allVariables;
  for (let i = 0; i<allVars.length; i++) {
      allVariables += allVars[i] + ", ";
  }
  console.log('Here are the complete list: ' + allVariables + '.');
  callback();
}

As Marvin mentioned, you can also use .join() to get the all variables in the array in one string.

function totalUp(allVars, callback){
  let allVariables = allVars.join(", ");
  console.log('Here are the complete list: ' + allVariables + '.');
  callback();
}

Second one is to pass it as an object

let allVars = {
    a: "this is a.",
    b: "this is b."
}

Upvotes: 1

Marvin Fischer
Marvin Fischer

Reputation: 2572

With ES6

You can use parameter destructuring for it:

function test(callback, ...params) {
    console.log(params); // ["a", "b"];
    console.log('Here are the complete list: ' + params.join(", ") + '.');
}

test(callback, "a", "b");

Without ES6

function test(params, callback) {
    console.log(params); // ["a", "b"];
    console.log('Here are the complete list: ' + params.join(", ") + '.');
}

test(["a", "b"], callback);

Upvotes: 1

Related Questions