forEach循环中return 跳出失败及解决方法

var temp=['1','2']
temp.forEach(e=>{
    
    
	if(e=='2'){
    
    
		return
	}
})

这样的forEach中使用return会跳出失败,因为forEach()无法在所有元素都传递给调用的函数之前终止遍历
最好的解决方法是换成for循环

var temp=['1','2']
for(let i=0;i<this.temp.length;i++){
    
    
	if(this.temp[i]=='2'){
    
    
		return
	}
}

同样,break在forEach中也无法使用会报错,换成for可以

猜你喜欢

转载自blog.csdn.net/weixin_43797908/article/details/118673100