休息;vs继续;vs回报; [英] break; vs continue; vs return;
问题描述
我更新了一些代码以添加新功能,并且看到了一些我不理解的内容.
I updated a little the code to add new functionality and I saw something I don't understand.
在代码中,我看到:
foreach() { ...
if() ...
break;
elseif() ...
continue;
}
我还看到了:
function() {
// ...
for($nl = 0; ...
if() ...
return true;
}
我读到 break;
将停止循环, continue
将跳过循环直至下一次迭代,而 return
将退出该函数.
I read that break;
will stop the loop, continue
will skip the loop to the next iteration and return
will exit the function.
我不明白的是为什么要编码这种样式?为什么不使用类似这样的东西:
What I don't understand is why coding that style? Why not use something like:
function() {
// ...
for($nl = 0; ...
if() ...
$returnValue = true;
else {
$returnValue = false;
}
}
return $returnValue;
}
还是for循环中有相同的想法?
or same idea in the for loops?
推荐答案
使用诸如 break
和 continue
之类的关键字可以使代码比您建议的更容易阅读
Using keywords such as break
and continue
can make the code far easier to read than what you propose.
特别是如果您要嵌套if/else语句超过一个级别.
Especially if you are nesting if/else-statements more than one level.
在这篇文章中比较下面的代码片段,哪一个更容易阅读?他们两个都输出相同的确切内容,而 $ A
是 array(1,2,4,4,3,4)
.
Compare the snippets further down in this post, which one is easier to read?
Both of them output the same exact thing, and $A
is array (1,2,4,4,3,4)
.
在循环中(在函数内部)返回
可以节省宝贵的CPU周期,如果您知道不需要进一步循环,为什么这样做?
A return
in a loop (inside a function) can save precious CPU cycles, if you know you don't need to loop any further, why do it?
$not_even_found = false;
foreach ($A as $v) {
if ($v != 1) {
if ($not_even_found) {
} else if ($v % 2 != 0) {
$not_even_found = true;
} else {
echo "$v\n";
}
}
}
我想输入可读的代码.
foreach ($A as $v) {
if ($v == 1)
continue;
if ($v % 2 != 0)
break;
echo "$v\n";
}
这篇关于休息;vs继续;vs回报;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!