2017-08-25 35 views
0

所以我期待在一块是困惑我的代码,尽管读的解释或两个:拆开函数表达式 - 用几行挣扎/参数

下面的代码..

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,所以在函数被调用之前没有什么可以实际提醒的?它很像一个'开'按钮?

对不起,这很长,在此先感谢!

+0

'queue'是数组,和'shift'返回该阵列,这恰好是一个函数中的第一项,和功能调用'(参数)' – adeneo

+0

功能在他们被叫之前不要做任何事情。一个IIFE立即调用该函数,但是命名函数通常被定义一次,因此可以通过不同的输入重复调用它们。 – Barmar

回答

1

为了清楚起见,我已经在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这意味着你将调用每个方法从puzzlers与价值2applyAndEmpty的结果将不再是3,而只是2,因为输入变量永不改变。所以如果你不存储调用puzzler方法的结果,你可能会完全跳过它们,并立即返回输入参数。

+0

Hey Thijs,谢谢你的回复,很棒的细节!我现在只是想知道,'for'循环如何知道它正在队列中运行并且没有输入? @Thijs –

+0

不客气!你能改说你的问题吗?我不确定你想知道什么。 – Thijs

+0

'//遍历队列中的所有项目。对于(var i = 0; i

0

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

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