gpt4 book ai didi

javascript - 使用动态参数数调用动态函数

转载 作者:IT老高 更新时间:2023-10-28 13:18:37 24 4
gpt4 key购买 nike

我正在寻找一个技巧。我知道如何在 JavaScript 中调用动态的任意函数,传递特定的参数,如下所示:

function mainfunc(func, par1, par2){
window[func](par1, par2);
}

function calledfunc(par1, par2){
// Do stuff here
}

mainfunc('calledfunc', 'hello', 'bye');

我知道如何使用 mainfunc 中的 arguments 集合来传递可选的、无限制的参数,但是,我不知道如何将任意数量的参数发送到 mainfunc 被动态发送到 calledfunc;我怎样才能完成这样的事情,但是使用任意数量的可选参数(不使用那个丑陋的 ifelse)?

function mainfunc(func){
if(arguments.length == 3)
window[func](arguments[1], arguments[2]);
else if(arguments.length == 4)
window[func](arguments[1], arguments[2], arguments[3]);
else if(arguments.length == 5)
window[func](arguments[1], arguments[2], arguments[3], arguments[4]);
}

function calledfunc1(par1, par2){
// Do stuff here
}

function calledfunc2(par1, par2, par3){
// Do stuff here
}

mainfunc('calledfunc1', 'hello', 'bye');
mainfunc('calledfunc2', 'hello', 'bye', 'goodbye');

最佳答案

使用函数的apply方法:-

function mainfunc (func){
window[func].apply(null, Array.prototype.slice.call(arguments, 1));
}

编辑:在我看来,稍微调整一下会更有用:-

function mainfunc (func){
this[func].apply(this, Array.prototype.slice.call(arguments, 1));
}

这将在浏览器之外工作(this 默认为全局空间)。在 mainfunc 上使用 call 也可以:-

function target(a) {
alert(a)
}

var o = {
suffix: " World",
target: function(s) { alert(s + this.suffix); }
};

mainfunc("target", "Hello");

mainfunc.call(o, "target", "Hello");

关于javascript - 使用动态参数数调用动态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/676721/

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