2016-10-11 60 views
1

我感到很尷尬,問這樣一個基本問題。但是,如果這是我的知識的根本或簡單的差距,我寧願得到一個解釋,爲什麼我可以儘快開始制定好習慣,而不是晚些時候。For循環if語句不遍歷整個數組

我有一個函數,它接受一個字符串作爲參數並將其與數組值進行比較。

function validateHello(greetings){ 
var hello = ['hello','ciao','salut','hallo', 'hola', 'ahoj','czesc']; 
    for(var i = 0; i < hello.length; i++){ 
    if(greetings === hello[i]){ 
     return true; 
    }else{ 
     return false; 
    } 

    } 

} 

看來,我每次運行這個for循環的時候,它只檢查第一陣列hello[0]隨後便出現斷裂。我怎樣才能阻止這種情況發生?返回true後,我嘗試使用continue;,但那並沒有解決它。我覺得我應該知道這一點,但我完全是腦筋急轉彎,不知道爲什麼。 謝謝!

回答

7

這是因爲你的return false說法,你應該把它外循環並刪除else聲明:

function validateHello(greetings){ 
var hello = ['hello','ciao','salut','hallo', 'hola', 'ahoj','czesc']; 
    for(var i = 0; i < hello.length; i++){ 
    if(greetings === hello[i]){ 
     return true; 
    } 
    } 
    return false; 
} 

說明:當greetings說法是不等於第一要素,'hello',那麼代碼將執行else語句,該語句返回false並停止函數執行。

2

您的return聲明正在破壞該函數。如果您刪除return語句,它將循環遍歷整個數組(儘管看起來您實際上沒有做任何事情,所以我不知道您會如何知道這一點)。

如果你只是想,如果greetings是數組中返回true,那麼這就是你要找的內容:

function validateHello(greetings){ 
var hello = ['hello','ciao','salut','hallo', 'hola', 'ahoj','czesc']; 
    for(var i = 0; i < hello.length; i++){ 
    if(greetings === hello[i]){ 
     return true; 
    } 
    } 
    return false; 
} 

注意返回錯誤已經被移動到循環之外。這樣,只要找到greetings就會立即返回true,否則它將完成循環,然後返回false。

0

我在代碼中添加備註並更改錯誤的部分。 刪除else塊,並將return false;for循環中取出。這將使完整的for循環。只有if聲明的條件是truefor循環將return。如果for循環沒有返回,則會執行下面的return false;語句。

function validateHello(greetings){ 
    var hello = ['hello','ciao','salut','hallo', 'hola', 'ahoj','czesc']; 
    for(var i = 0; i < hello.length; i++){ 
     if(greetings === hello[i]){ 
      return true; 
     } 
     /* if you add a else block here. it means you want your 'else condition' to be checked in every single loop. Since 'if statement has a 'return' and 'else' statement has a 'return'. So if there is a 'else' here, no matter what condition you add , your for loop can only be executed once. */ 
    } 
    return false; // only the for loop is over and no return. this statement will be executed. 
}