fre*_*hie 44 javascript for-loop
我有一个for循环,我想退出这样:
function MyFunction() {
for (var i = 0; i < SomeCondition; i++) {
if (i === SomeOtherCondition) {
// Do some work here.
return false;
}
}
// Execute the following code after breaking out of the for loop above.
SomeOtherFunction();
}
Run Code Online (Sandbox Code Playgroud)
问题是在// Do some work here.语句执行之后,我想退出for循环,但仍然希望执行整个for循环下面的代码(下面的所有内容// Execute the following code after breaking out of the for loop above.).
该return false语句确实退出for循环,但它也退出整个函数.我该如何解决?
Chr*_*ler 10
使用break或continue语句
function MyFunction() {
for (var i = 0; i < SomeCondition; i++) {
if (i === SomeOtherCondition) {
// Do some work here
break;
}
}
SomeOtherFunction();
SomeOtherFunction2();
}
Run Code Online (Sandbox Code Playgroud)
或继续处理条件以外的项目
function MyFunction() {
for (var i = 0; i < SomeCondition; i++) {
if (i != SomeOtherCondition) continue;
// Do some work here
}
SomeOtherFunction();
SomeOtherFunction2();
}
Run Code Online (Sandbox Code Playgroud)
有几个人提出break了解决方案,这确实是问题的最佳答案.
但是,为了完整起见,我觉得我还应该补充说return,通过将if()条件的内容包装在闭包函数中,可以在保留语句的同时回答问题:
function MyFunction() {
for (var i = 0; i < SomeCondition; i++) {
if (i === SomeOtherCondition) {
function() {
// Do some work here
return false;
}();
}
}
SomeOtherFunction();
SomeOtherFunction2();
}
Run Code Online (Sandbox Code Playgroud)
正如我所说,break在这种情况下可能是一个更好的解决方案,因为它是问题的直接答案,并且闭包确实引入了一些额外的因素(例如更改值this,限制函数内部引入的变量的范围等).但它值得提供作为解决方案,因为它是一种有价值的学习技术,如果不一定在这个特殊场合使用,那么肯定是为了未来.