gpt4 book ai didi

javascript - 避免 eval(),我需要一种将多个参数传递给变量函数的方法

转载 作者:行者123 更新时间:2023-11-28 20:31:42 26 4
gpt4 key购买 nike

尝试将多个参数传递给变量函数调用..

function myFunction(myvar,time){
alert(myvar);
}

t_function = "myFunction";
t_params = "haha,hehe";
window[t_function](t_params);

我基本上需要模仿这个调用

myFunction("haha","hehe");

我无法在变量函数调用中设置特定数量的参数,例如

// I will not know how many params a function will need.
window[t_function](t_params1,t_params2,etc);

有什么想法吗?我很想使用 eval。

------最终这样做了-----

函数 myFunction(myvar1,myvar2){ 警报(myvar1 +“和”+ myvar2);

}

t_function = "myFunction";
t_params = [];
t_params[0] = "haha";
t_params[1] = "hehe";

window[t_function].apply(this,t_params);

感谢所有人,特别是梦想家约瑟夫

最佳答案

您需要apply ,它接受函数中 this 的值和一个参数数组:

window[t_function].apply(this,[arg1,arg2,...,argN]);

该函数将接收它:

function myFunction(arg1,arg2,...,argN){...}

传递到被调用函数的每个值都可以通过类似数组的参数来访问。当参数是动态的时,这尤其有用。因此,您可以执行以下操作:

function myFunction(){
var arg1 = arguments[0]; //hello
var arg2 = arguments[1]; //world
}

//different ways of invoking a function
myFunction('hello','world');
myFunction.call(this,'hello','world');
myFunction.call(this,['hello','world']);

关于javascript - 避免 eval(),我需要一种将多个参数传递给变量函数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16228150/

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