gpt4 book ai didi

javascript - 返回动态值作为参数

转载 作者:行者123 更新时间:2023-11-28 12:46:56 26 4
gpt4 key购买 nike

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

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
}

关于javascript - 返回动态值作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6745529/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com