如何提前退出 TypeScript 文件中的函数?
checkIfFollowed(){
this.currentUserInfos.followed.forEach(element => {
if(18785 == 18785){
console.log('its true');
this.alreadyFollowed = true;
return; // Exit checkIfFollowed() here
}
});
this.alreadyFollowed = false;
console.log('the end');
return;
}
当我运行它时,它已完全执行,但它应该在第一个之后退出:
'its true'
但是在我的控制台中,我得到:
its true
its true
the end
Foreach 按预期循环了 2 次,但为什么该方法在点击“return”后没有停止?
我并不是试图退出 forEach,而是结束 foreach 中的“checkIfFollowed”方法。
不应打印“the end”。
最佳答案
另一种方法,使用 for
循环:
checkIfFollowed() {
for (let i = 0; i < this.currentUserInfos.followed.length; ++ i) {
if (18785 == 18785) {
console.log('its true');
this.alreadyFollowed = true;
return; // exit checkIfFollowed() here
}
}
this.alreadyFollowed = false;
console.log('the end');
return;
}
关于javascript - 提前退出 forEach 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43179830/