Preface: forEach no return value! ! ! Set the return value and no return value.
One, for comparison loop
var ARR = [ . 1 , 2 , . 3 , . 4 , . 5 ]; function Test () { for ( var I = 0 ; I <arr.length; I ++ ) { IF (ARR [I] == . 3 ) { return ' Found 3, the cycle terminates and ' ; } the console.log (ARR [I]); } } Test ();
Run Results: 1 output. And terminates the cycle. 4, 5 continues to output no later;
②、console.log(test());
var ARR = [ . 1 , 2 , . 3 , . 4 , . 5 ]; function Test () { for ( var I = 0 ; I <arr.length; I ++ ) { IF (ARR [I] == . 3 ) { return ' Found 3, the cycle terminates and ' ; } the console.log (ARR [I]); } } the console.log (Test ());
Second, in contrast forEach loop
var ARR = [ . 1 , 2 , 3 , . 4 , . 5 ]; function test2 () { arr.forEach (function (Item) { IF (Item == 3 ) { return ' found a 3, and this cycle is skipped ' ; } the console.log (Item); }); } test2 ();
The result: the output 1,2,4,5. Did not terminate the loop, but when the item == 3, when, out of this cycle
②、console.log(test2());
②、console.log(test2());
var ARR = [ . 1 , 2 , 3 , . 4 , . 5 ]; function test2 () { arr.forEach (function (Item) { IF (Item == 3 ) { return ' found a 3, and this cycle is skipped ' ; } the console.log (Item); }); } the console.log (test2 ());
The result: the output of 1,2,4,5, undefined. And no output we need, but returned an undefined.
Third, the solution
Array.some () application
var ARR = [ . 1 , 2 , 3 , . 4 , . 5 ]; function Test3 () { arr.some (function (Item) { IF (Item == 3 ) { return ' found 3, and terminates the cycle " ; } the console.log (Item); }); } the console.log (Test3 ());
Run Results: output 1,2, undefined. Termination of the cycle, but no output we need, but returned an undefined.
Array.every () results and some () the same result
Transfer from https://blog.csdn.net/w390058785/article/details/79916266