简体   繁体   中英

How to construct a JavaScript for loop with a function

I'm constructing a loop for with a function.

The function loop takes a value, a test function, an update function, and a body function. Each iteration, it first runs the test function on the current loop value and stops if that returns false. Then it calls the body function, giving it the current value. Eventually, it calls the update function to create a new value and starts from the beginning.

loop(10, n => n > 0, n => n - 1, console.log);

function loop(a, b, c, d) {

    let currentValue = a;
    let i;
    for (i = 0; i < currentValue; i++) {
        if (b(currentValue)) {
            d(currentValue);
            update(c);

            function update(c) {
                var executeUpdate = c(currentValue);
                currentValue = executeUpdate;
            };
        } else {
            return;
        }
    };
}


// OUTPUT: 10, 9, 8, 7, 6

Why does this function stop at 6 instead of 1 ?

You can use few console.logs to see it.

Actually the for-cycle ends when currentValue and i equals 5, therefore the condition is not met and cycle terminates.

However your condition does not make any sense, you are comparing true to some number (as you can see in the logs)

 loop(10, n => n > 0, n => n - 1, console.log); function loop(a, b, c, d) { let currentValue = a; let i; for (i = 0; i < currentValue; i++) { console.log(i, currentValue); console.log(b(currentValue), currentValue) if (b(currentValue) < currentValue) { d(currentValue); update(c); function update(c) { var executeUpdate = c(currentValue); currentValue = executeUpdate; }; } else { console.log('I am not here'); return; } } console.log('finished', i, currentValue); } 

 function update(c) { var executeUpdate = c(currentValue); console.log('value of exeucteUpdate: ',executeUpdate, 'when i:', i) currentValue = executeUpdate; }; 

Do a console.log at your update function, you will notice when i == 4, executeUpdate is 5 and you updated the value of forloop and hence the loop terminates at this particular loop

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