简体   繁体   English

我可以结束while循环功能吗?

[英]Can i end While loop with function?

I tried to google this and i think it can't be done but i have to ask anyway. 我试图谷歌这个,我认为它不能做,但我还是要问。 If i have while loop? 如果我有while循环?

while ($smth > 1)
{
  func();
}

Is there a way i could exit the while loop immediately with that function inside it? 有没有办法可以立即退出while循环中的那个函数? Maybe that function returns something that stop loop? 也许该函数返回停止循环的东西? I tried 我试过了

func(){ 
return break;}

but this doesn't work. 但这不起作用。

It's not possible the way you've done it -- you can't return a break. 你做的不可能 - 你不能回来休息。 But you can return a value that could signal to exit the loop. 但是你可以返回一个可以指示退出循环的值。

function func() {
  return true
}

And then 接着

while($smth > 1) {
  if(func()) break;
}

This will run the function, but it will also check it's return value to verify it does not need to exit the loop. 这将运行该函数,但它也将检查它的返回值以验证它不需要退出循环。 If the function returned true, the if statement is satisfied and so a break will occur. 如果函数返回true,则if语句得到满足,因此将发生break If the function doesn't return explicitly, the if will not be satisfied. 如果函数未明确返回,则不满足if

You sort of can get out of that while loop from inside that function by throwing an exception. 通过抛出异常,你可以从该函数内部循环出来。 Your teammates will not like you anymore, however. 但是,你的队友不再喜欢你了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM