花越来越多的时间学习 JS,我很喜欢它。然而,当我开始处理稍微复杂的函数(IIFE、匿名等)时 - 我开始挣扎并且喜欢一些指针。感谢所有帮助和建议来解释为什么我的代码行(第 15 行)造成如此多的悲伤!
分配说明如下:
- 构建一个函数并将其分配给名为 applyAndEmpty 的变量。
- 该函数应接受输入数字和函数队列 作为参数。
- 使用for循环,按顺序调用队列中的函数 输入数字,其中每个函数的结果成为下一个函数 函数的输入。此外,队列应该是空的 函数被调用。
- 最后,使用提供的 start 调用 applyAndEmpty 函数 变量和拼图队列作为参数,并警告结果。
到目前为止,我知道我已经正确设置了 for 循环,并且在调用实际函数方面处于正确的轨道上,但我根本无法弄清楚循环中的最后一行。我意识到我需要使用数组移位方法才能按顺序开始清空数组,但是,我不确定如何将输入参数应用于每个函数,将其存储为输入,然后在删除时继续循环返回结果之前的函数。
// The following array and 'start' variable are given (by the assignment):
var puzzlers = [
function(a) { return 8 * a - 10; },
function(a) { return (a - 3) * (a - 3) * (a - 3); },
function(a) { return a * a + 4; },
function(a) { return a % 5; }
];
var start = 2;
// My code begins below:
var applyAndEmpty = function(input,queue) {
for(var i = 0; i < queue.length; i++) {
input = queue[i].shift(); // This is my problem area - I simply don't understand!
}
return input;
};
alert(applyAndEmpty(start,puzzlers));
最佳答案
通过此语法,您将在数组中的项目(而不是数组)上调用 shift
。所以代替这个:
input = queue[i].shift()
试试这个:
var func = queue.shift() //get the function from the array
input = func(input) //call the function, I'd recommend you don't overwrite your param, rather store to another var (helpful in debugging)
由于这是一项作业,我不会修复其余部分(授人以渔......),但作为提示,您应该存储之前的答案,以便您可以将其用作当前函数的参数。
关于javascript - 数组作为队列并在另一个内部调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30309845/