Say you have a for
loop:
假设您有一个for
循环:
const list = ['a', 'b', 'c']
for (let i = 0; i < list.length; i++) {
console.log(`${i} ${list[i]}`)
}
If you want to break at some point, say when you reach the element b
, you can use the break
statement:
如果要在某个时刻中断,例如说到达元素b
,可以使用break
语句:
const list = ['a', 'b', 'c']
for (let i = 0; i < list.length; i++) {
console.log(`${i} ${list[i]}`)
if (list[i] === 'b') {
break
}
}
You can use break
also to break out of a for..of loop:
您还可以使用break
来打破for..of循环:
const list = ['a', 'b', 'c']
for (const value of list) {
console.log(value)
if (value === 'b') {
break
}
}
Note: there is no way to break out of a
forEach
loop, so (if you need to) use eitherfor
orfor..of
.注意:无法中断
forEach
循环,因此(如果需要)可以使用for
或for..of
。
翻译自: https://flaviocopes.com/how-to-break-for-loop-javascript/