分解一个函数表达式 - 与一对夫妇的斗争 Lines/Parameters

Taking apart a Function Expression - Struggling with a Couple Lines/Parameters

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

这是代码..

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)); 我知道调用函数然后提醒它。为什么我必须先调用函数才能 alert/console 记录等?这是不是因为它不是 IIFE,所以在函数被调用之前没有什么可以实际警告的?它很像一个 'on' 按钮?

抱歉,这很长,提前致谢!

为了清晰起见,我稍微编辑了 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,因为输入变量永远不会改变。因此,如果您不存储调用拼图方法的结果,您不妨完全跳过它们,直接 return 输入参数。

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

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