拆开函数表达式 - 为几行/参数而苦苦挣扎



所以我正在看一段代码,尽管阅读了一两个解释,但它让我感到困惑:

这是代码..

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;
var applyAndEmpty = function (input, queue) {
var length = queue.length;
for (var i = 0; i < length; i++) {
input = queue.shift()(input);
}
return input;
};
alert(applyAndEmpty(start, puzzlers));

我理解其中的大部分内容,但细分会很棒,真正让我难以置信的是这一行的开头和结尾input = queue.shift()(input);我知道它正在使用输入来存储结果,但为什么呢为什么末尾还有一个输入参数

PS 我知道这行alert(applyAndEmpty(start, puzzlers));调用函数然后提醒它。为什么我必须先调用一个函数才能发出警报/控制台日志等?这是因为它不是 IIFE 并且因此在调用函数之前没有什么可以实际警报的吗?它很像一个"开"按钮?

对不起,这太长了,提前谢谢!

为了清楚起见,我稍微编辑了for循环中的代码。

// This array contains 5 items, each item is a function which takes a single param and returns a number.
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; }
];
// The start value is 2.
var start = 2;
var applyAndEmpty = function (input, queue) {
// Get the number of items in the queue.
var length = queue.length;
// Iterate over all the items in the queue.
for (var i = 0; i < length; i++) {
// Remove the item at index 0 from the queue, the item is stored in the var.
var itemMethod = queue.shift();
// Execute the method, pass it the current value as input param. The result 
// of the method will be placed back into the input variable.
input = itemMethod(input);
}
// Return the modified input value.
return input;
};
// Runs the applyAndEmpty method and shows the output in an alert.
alert(applyAndEmpty(start, puzzlers));
// The breakdown of the for loop:
// i = 0, input = 2 -> return 8 * 2 - 10 = 6
// i = 1, input = 6 -> return (6-3) * (6-3) * (6-3) = 27
// i = 2, input = 27 -> return 27 * 27 + 4 = 733
// i = 3, input = 733 -> return 733 % 5 = 3
// And thus the alert says three.

如果不将当前itemMethod的结果放回input则意味着您将使用值2puzzlers调用每个方法。applyAndEmpty的结果将不再是 3,而只是 2,因为输入变量永远不会改变。因此,如果您不存储调用益智器方法的结果,则不妨完全跳过它们并立即返回输入参数。

这只是一种链接数组中函数的方法,以便将第一个函数的结果传递给第二个函数,将第二个函数的结果传递给第三个函数,依此类推......

f = [ a => 8 * a - 10,
a => (a-3) * (a-3) * (a-3),
a => a * a + 4,
a => a % 5 ]
console.log(f[3](f[2](f[1](f[0](2)))))                // 3
console.log(f.pop()(f.pop()(f.pop()(f.pop()(2)))))    // 3
console.log((a => a % 5)((a => a * a + 4)((a => (a-3) * (a-3) * (a-3))((a => 8*a - 10)(2)))))   // 3

最新更新