Why this code doesn't return false?

This question already has an answer here:

  • How to short circuit Array.forEach like calling break? 24 answers

  • The return false is the return of the anonymous function used in the forEach . So it does not return anything for every . If you want to use forEach and return false, you have to do like this :

    function every(array, predictate) {
        var result = true;
    
        array.forEach(function(x) {
            if (!predictate(x)) {
                result = false;
            }
        });
    
        return result;
    }
    

    Your return false statement is for the forEach callback function, not for the external every .

    every will always return true unless you change it to something like:

    function every(array, predictate){
        var retValue = true;
        array.forEach(function(x){
        if (!predictate(x))
            {
            retValue = false;
            }
        });
        return retValue;
    }
    
    链接地址: http://www.djcxy.com/p/70060.html

    上一篇: 我如何摆脱forEach或重新构造我的功能?

    下一篇: 为什么这段代码不会返回false?