我想使用数组作为参数来调用函数:
const x = ['p0', 'p1', 'p2'];
call_me(x[0], x[1], x[2]); // I don't like it
function call_me (param0, param1, param2 ) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
有路过的内容的一种更好的方式x进入call_me()?
我正在寻找一个关于这个的伎俩.我知道如何在Javascript中调用动态的任意函数,传递特定的参数,如下所示:
function mainfunc(func, par1, par2){
window[func](par1, par2);
}
function calledfunc(par1, par2){
// Do stuff here
}
mainfunc('calledfunc', 'hello', 'bye');
Run Code Online (Sandbox Code Playgroud)
我知道如何在mainfunc中使用arguments []集合传递可选的无限参数,但是,我无法想象如何向mainfunc发送任意数量的参数以动态发送到calledfunc ; 我怎么能完成这样的事情,但有任意数量的可选参数(不使用丑陋的if-else)?:
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');
Run Code Online (Sandbox Code Playgroud) 所以我正在尝试创建一个接收数组的函数(我猜它更像是一个JSON对象,或者我们被告知)对象并返回一个基于该数组的值,但我一直收到错误,所以我'我很确定我做错了.
我对JavaScript很新,所以对我很轻松.此外,我发现这个线程与我问的问题类似,但我不太明白这个问题(因此它是答案).
这是我们给出的对象的示例:
var returned_json = {
"nike_runs": [
{
"start_time": "2011-03-11T19:14:44Z",
"calories": 12.0,
"distance_miles": "0.10",
"total_seconds": 288.0,
"average_pace":"50.47"
},
{
"start_time": "2011-03-11T19:41:25Z",
"calories": 7.0,
"distance_miles": "0.06",
"total_seconds": 559.0,
"average_pace": "165.19"
},
{
"start_time": "2011-03-11T20:27:45Z",
"calories": 197.0,
"distance_miles": "1.63",
"total_seconds": 8434.0,
"average_pace": "86.22"
},
...
]
}
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
function getExp (returned_json) {
var exp;
for (var i = 0; i <= returned_json.nike_runs.length; i++) {
exp += returned_json.nike_runs[i].calories;
}
return exp;
}
Run Code Online (Sandbox Code Playgroud)
它返回一个错误:
TypeError: returned_json.nike_runs[i] is undefined
Run Code Online (Sandbox Code Playgroud)
我认为这与我没有定义我希望传递给函数的对象类型的事实有关,但我的研究告诉我无所谓.
救命?:( …
我有这个功能:
function getTotal () {
var args = Array.prototype.slice.call(arguments);
var total = 0;
for (var i = 0; i < args.length; i++) {
total += args[i];
}
return total;
}
Run Code Online (Sandbox Code Playgroud)
让我们说我有一个充满数字的数组,我不知道它的长度:
var numArray = [ ..., ... ];
Run Code Online (Sandbox Code Playgroud)
如何getTotal通过传入numArray作为参数的每个元素来调用该函数?