返回动态值作为参数

Return dynamic values as arguments

本文关键字:参数 动态 返回      更新时间:2023-09-26

如何将动态参数传递给函数,例如

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

如何传递参数从getDrink()正确 -我只做接收'可乐',而不是'百事可乐'。

如果你想发送动态数量的参数,使用apply函数:

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

也可以使用call函数:

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

如果您想访问函数中的所有参数,您可以使用arguments数组

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

如果您希望getDrink返回包含'pepsi''cola'的数组,则语法为['pepsi', 'cola']

我不太确定这是不是你想要的……

注意,这仍然会给你:

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

三个参数,其中最后一个是数组,而不是四个参数

如果您希望使用四个字符串参数调用iLike,您可能希望像这样调用它:

function getDrink(){
    return (customvar == 1 ? ['pepsi','cola'] : ['drpepper']);
}
iLike.apply(this, ['peanuts', 'pizza'].concat(getDrinks()))

可以使用arguments对象:

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

如果你想从getDrink返回'pepsi'和'cola'(在一个变量中),你可以使用数组:

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

解决方案是使用数组,并使用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"]