文本介绍如何JavaScript中中断for或for..of循环的方法
假设我们使用这样一个for循环:
/**
* 前端教程网
* http://www.pipipi.net
*/
const list = ['a', 'b', 'c']
for (let i = 0; i < list.length; i++) {
console.log(`${i} ${list[i]}`)
}
如果您想在某个时候中断,比如说到达数组项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
}
}
你也可以使用break来跳出for…of…循环:
const list = ['a', 'b', 'c']
for (const value of list) {
console.log(value)
if (value === 'b') {
break
}
}
注意:无法中断forEach循环,因此如果需要跳出循环,请使用for或for..of。