简体   繁体   中英

I don't understand my for loop?

My question may silly, so apologize in advance. My instructions were to build a function that iterated over a queue of functions. The answer is at the bottom....below the puzzlers array.

Can someone explain why the command in the for-loop is input = queue.shift()(input); . I understand that I had to use the shift method to empty the queue. This exercise was confusing to me to begin with, but creating input = queue.shift()(input); is still strange to me. any fundamental explanations would be greatly appreciated. If you need more info, please let me know.....thank you in advance.

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

queue is an array, so queue.shift() takes the first item out of the array (removing it) and returns it.

Now, since queue is holding functions, you're telling whatever function was at the beginning of queue to run with a parameter of input .

For a more concrete example, lets say the first item in queue was a function called function1 . You can think of queue.shift() as being replaced by function1 once it evaluates—so queue.shift()(input); becomes function1(input);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM