I’ve just written about if-else optimization, and it occurs to me that you can’t always use returns there. Sometimes you also need to use break or continue, so remember the difference.
Continue, break, return
- Continue: Skips the current loop of the loop, the statements following the current loop are not executed, and the next loop is executed
- Break: Ends the loop and continues the rest of the function
- Return: terminates the function (regardless of how many levels of nesting)
I’ll illustrate with a double loop of code
ifElse()
function ifElse() {
console.log("ifElse")
const arr = ['The first'.'Second'.'The third']
const arr2 = ['〇'.'一'.'二']
for (let i = 0; i < arr.length; i ++) {
console.log(arr[i])
for (let j = 0; j < arr2.length; j ++) {
console.log(arr2[j])
}
}
console.log("End of loop")}Copy the code
Take a look at what the code should look like:
First print “ifElse”; After printing the first value of the first array, print the three values of the second array; It prints the second value of the first array, and then the three values of the second array; Print the third value of the first array, then print the three values of the second array again; Finally, print “end of loop”.
Execute:
No problem, let’s move on
return
This is when we’reconsole.log(arr2[j])
Add a judgment above:if (j == 1) return
(I won’t post the code, it takes up too much space); Because we’re usingreturn
So with that said,return
Is the end of the function, will directly end the whole function, so the print order should be: printifElse
-> Print the first value of the first array -> print the first value of the second arrayreturn
End). Graph:
continue
We will beif (j == 1) return
In thereturn
Switch tocontinue
In short, it meansfromcontinue
Let’s skip the next statement and go through the next loop, so the order of printing this time should be: PrintifElse
-> Print the first value of an array -> print the first and third value of the second array in turn (because the second value is skipped by continue) -> print the second value of the first array… -> Prints “End of loop”. Graph:
break
And finally we putif (j == 1) return
In thereturn
Switch tobreak
“, which means to end the loop. And we can see,break
}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
The last
A return terminates only the innermost function, if it is a function within a function. For example:
test()
function test() {
console.log("Start")
let a = function () {
console.log("Function")
return
console.log("End of function")
}
a()
console.log("Run out of function")
return
console.log("The end")}Copy the code
likea
In the functionreturn
The end is justa
Function, does not endtest
And thea()
After thereturn
And what ends up beingtest
the