嵌套if語句聲明每個語句返回false

[英]Nested if statements declaring return false for each one


Say I have the following code:

說我有以下代碼:

function a() {
    if ($a) {
        if ($b) {
            if ($c) {
                // do something
            }
            return FALSE
        }
        return FALSE;
    }
    return FALSE;
}

In this instance do I need all the return falses or will it sort of cascade to the last one if I remove both the inner ones?

在這個例子中,我是否需要所有的返回falses,或者如果我刪除兩個內部的那些它會級聯到最后一個?

Thanks

謝謝

6 个解决方案

#1


3  

if ($a && $b && $c) {
    //do something
    return TRUE;
} else {
    return FALSE;
}

#2


0  

It will cascade down the list. You don't need each return false call.

它會在列表中向下級聯。你不需要每個都返回錯誤的電話。

#3


0  

It will fall/cascade through to the last one.

它會下降/級聯到最后一個。

But you may also need a return true; in your //do something part as the return false; will be called otherwise.

但你可能還需要一個真實的回報;在你的//做一些部分作為返回false;否則將被稱為。

The function will continoue to run until one of the three things happen:

該功能將繼續運行,直到發生以下三種情況之一:

  • a return statement is executed
  • 執行return語句
  • the closing } of the function is reached
  • 達到了該函數的結束
  • an uncatched Exception or (Fatal) error occurs
  • 發生未捕獲的異常或(致命)錯誤

#4


0  

It will continue on through, however, this may not be what you want, as such a return will end the function altogether and might skip something you want done.

它會繼續,但是,這可能不是你想要的,因為這樣的返回將完全結束這個功能,可能會跳過你想要的東西。

#5


0  

Use something like this for a straightforward and easily understood representation:

使用類似的東西可以直觀易懂地表達:

function a() {
    if ($a) {
        if ($b) {
            if ($c) {
                // do something
                return TRUE; // or something other than TRUE
            }
        }
    }
    return FALSE;
}

#6


0  

Short answer; you can safely remove all "return false;" except the last one and it will still work the same.

簡短的回答;你可以安全地刪除所有“return false;”除了最后一個,它仍將工作相同。

Once it reaches the end of an if-statement it will jump out of it and continue in the previous block of code ( a block is defined by a { and }). For example, if $a is true but $b is not, it will enter the $a-block and then skip the $b-block, continuing right after it. When the $a-block has ended it will return to the previous block. See the following illustration:

一旦它到達if語句的末尾,它將跳出它並繼續前一個代碼塊(一個塊由{和}定義)。例如,如果$ a為真但$ b不為,則它將進入$ a-block,然后跳過$ b-block,繼續執行。當$ a-block結束時,它將返回上一個塊。請參見下圖:

function a() {
    if ($a) { // $a is true, enters block
        if($b) { // $b is false, skip block
            return true;
        }
        // end of $a-block reached, leave $a-block
    }
    return false; // return false and stop further execution
}

A cleaner way to write the above if-statements could be:

編寫上述if語句的更簡潔方法可以是:

If ($a && $b)
    return true;
return false;

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/11/22/7258c374538639a76976a994aa2041e9.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com