Home >Web Front-end >Front-end Q&A >What is the difference between foreach and for loop
Difference: 1. for loops through each data element through the index, while forEach loops through the data elements of the array through the JS underlying program; 2. for can terminate the execution of the loop through the break keyword, and forEach cannot; 3. for can control the execution of the loop by controlling the value of the loop variable, but forEach cannot; 4. for can call loop variables outside the loop, but forEach cannot call loop variables outside the loop; 5. Execution of for The efficiency is higher than forEach.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
(1) The for loop loops through each data element of the array by generating the index subscript of the array
forEach is a function method of an array defined by JavaScript that loops through the data elements of the array through the JavaScript underlying program
#(2) The for loop can terminate the execution of the loop through the break keyword
Call in forEach When executing the break program, an error will be reported
(3) The for loop can control the execution of the loop by controlling the value of the loop variable
The parameter storage data in the forEach loop is assigned by the underlying program and cannot be assigned or modified.
(4) The for loop can call loop variables outside the loop
forEach loop cannot call loop variables outside the loop
##(5) The execution efficiency of for loop is higher than that of forEach loop2. Comparison of for loop and forEach loopSince the syntax of the for loop and forEach loop looks like The for loop is more convenient and more reasonable. Why are there two loops, for loop and forEach? First of all, the execution of the for loop can only generate the index subscript value through the loop and then operate the data elements of the array through the index subscript. But forEach can store the index subscript data value by setting parameters, which is more convenient in operationBut the bottom layer of forEach uses the let keyword to declare variables and can only This keyword declares that variables cannot be modified
If you want to get Web front-end learning materials and source code, please click on the link below with your mobile phone to get a massive information package!
The above is the detailed content of What is the difference between foreach and for loop. For more information, please follow other related articles on the PHP Chinese website!