for loop naming
1. Demand background
When we use a double loop to search for a certain target, and after finding it we want to jump out of the entire double loop in the inner loop, we may think of using a flag bit to jump out of the outer loop when the outer loop determines that the flag bit is true.
For example:
const arr = [
['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9']
]
let flag = false
for (let i = 0; i < arr.length; i++) {
if (flag) break
for (let j = 0; j < arr[0].length; j++) {
if (arr[i][j] === '5') {
flag = true
break
}
console.log(i, j, arr[i][j])
}
}
As you can see, the loop stops after finding 5.
However, let’s share a more elegant way to achieve it, which is to use for loop naming .
2. Basic grammar
name: for()
:
name: name of for loop
For example:
fo:for (let i = 0; i < 4; i++) {
console.log(i)
}
The for loop naming only makes sense in combination with break and continue, and can only be used inside the loop.
3. Specific use
Let’s take the above case as an example:
const arr = [
['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9']
]
fo:for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[0].length; j++) {
if (arr[i][j] === '5') {
break fo
}
console.log(i, j, arr[i][j])
}
}
achieved the same effect
Of course, we can also implement it in combination with continue.
For example, if we want to take out the first element of each row, just
fo:for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[0].length; j++) {
console.log(i, j, arr[i][j])
if (j === 0) {
continue fo
}
}
}
In this way, when j === 1, you can jump out of the current round of the outer loop and directly enter the next round.
The advantages of double circulation may not be that great, but if it is multi-layered, it will be very comfortable to use.