简体   繁体   中英

Weird behavior in javascript function

This javascript should run the function func len times and then return whether it was successful all the times or not. Instead, the for loop is cancelled as soon as func returns false. How can this be explained? ( jsfiddle )

function do_something(func, len) {
    var res = true;
    for (var i = 0; i < len; i++) {
        res = res && func(i);
    }
    return res == true;
}

do_something(function(x) {
    console.log(x);
    return false;
}, 5);

do_something(function(x) {
    console.log(x);
    return true;
}, 5);

I would expect 0, 1, 2, 3, 4, 0, 1, 2, 3, 4 , but the output looks like this:

0
0
1
2
3
4

Because the first function returns false , res = res && func(0) will assign false to res . The next time the line is executed, ie res = res && func(1) , func(1) won't be executed because res is (and stays) false .

&& is short-circuiting . Given a && b , if a evaluates to false , b won't be evaluated at all.

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