How return terminates each iteration

question: I have customized an each iterative function to compare whether the two arrays are consistent. If a difference is found during traversal, exit the loop. There are some questions about how to exit the loop.
Code:

/* 
   
*/
const each = function(arr,callback){
    for(var i=0;i<arr.length;iPP){
        callback.call(arr[i],i,arr[i]);
    }
}


/* 
      -----
*/
const compare = function(arr1,arr2){
    if(arr1.length !== arr2.length){
        console.log("");
        return;
    }
    each(arr1,function(index,item){
        if(item !== arr2[index]){
            console.log("");
            return;
        }
    })
}


/* 
    -----
*/
const compare = function(arr1,arr2){
    if(arr1.length !== arr2.length){
        console.log("");
        return;
    }
    var breaked = false;
    each(arr1,function(index,item){
        if(breaked){
            return;
        }
        if(item !== arr2[index]){
            console.log("");
            breaked = true;
        }
    })
}

question: mode one, if it is not equal, the loop will continue to execute and will not be terminated. But the second way of use can terminate the loop. What is the difference between the two ways?

Mar.05,2021

add a line to the second compare function:


<strong>each</strong>callbackeachfor

if(breaked){
    return;
}

try adding console.log

Menu