mate64
mate64

Reputation: 10072

Return dynamic values as arguments

How can I pass dynamic arguments to a function, e.g

var customvar = 1; //example

  function iLike(){

      console.log("you like ... (I know how to receive the arguments!)")
  }

  function getDrink(){

       return (customvar == 1 ? ('pepsi','cola') : ('drpepper'));
  }

  iLike('peanuts', 'pizza', getDrink());

  iLike('peanuts', 'pizza', 'pepsi', 'cola'); // = result

How to pass arguments from getDrink() correctly - I do only do receive 'cola' but not 'pepsi'.

Upvotes: 0

Views: 1467

Answers (4)

sv_in
sv_in

Reputation: 14049

If you want to send dynamic number of arguments, use apply function:

getDrink.apply(this, ['pepsi', 'cola']);
getDrink.apply(this, ['pepsi', 'cola', '7up']);

You can also use call function:

getDrink.call(this, 'pepsi', 'cola');
getDrink.call(this, 'pepsi', 'cola', '7up');

If you want to access all the arguments in a function u can use arguments array

function getDrink() {
var first = arguments[0]; //pepsi
var secon = arguments[1]; //cola
}

Upvotes: 3

August Lilleaas
August Lilleaas

Reputation: 54593

The solution is to work with arrays, and use apply.

var customvar = 0;    

function iLike() {
    console.log(arguments);
}

function getDrink() {
    return (customvar == 1 ? ["pepsi", "cola"] : ["drpepper"]);
}

iLike.apply(this, ["peanuts", "pizza"].concat(getDrink()));
// ["peanuts", "pizza", "drpepper"]

Upvotes: 1

KooiInc
KooiInc

Reputation: 122916

You can use the arguments object for that:

function iLike(){
   var args = Array.prototype.slice.call(arguments); //convert to real array
   console.log('I like '+args[0]+', '+args[1]+' and '+args[2]);
}

If you want to return 'pepsi' as well as 'cola' (in 1 variable) from getDrink, you could use an array:

function getDrink(){
       return (customvar == 1 ? ['pepsi','cola'] : 'drpepper');
}

Upvotes: 1

David Hedlund
David Hedlund

Reputation: 129792

If you want getDrink to return an array containing 'pepsi' and 'cola' then the syntax is ['pepsi', 'cola']

I'm not quite sure if that's what you wanted...

Note that that would still give you:

iLike('peanuts', 'pizza', ['pepsi', 'cola'])

Three arguments, out of which the last is an array, rather than four arguments.

If you want iLike to be called with four string arguments, you might want to call it like this:

function getDrink(){
    return (customvar == 1 ? ['pepsi','cola'] : ['drpepper']);
}

iLike.apply(this, ['peanuts', 'pizza'].concat(getDrinks()))

Upvotes: 1

Related Questions