2017-02-21 76 views
0

我有一個if語句必須調用函數checkEmpty()爲每個條件。if語句檢查多個布爾條件

function checkFormFilled(evt){ 
    var isFilled; 
    if(checkEmpty('id1', 'class1') && //condition 1 
     checkEmpty('id2', 'class2') && //condition 2 
     checkEmpty('id3', 'class3') && //condition 3 
     checkEmpty('id4', 'class4')){ //condition 4 
     evt.preventDefault(); 
     isFilled = true; 
    } 
    return isFilled; 
} 

問題是,當條件1爲假(前述任一條件爲假),跳到evt.preventDefault()行,沒有得到調用其他以下checkEmpty()函數。

我想在所有條件返回true時調用evt.preventDefault()。

有沒有其他的方法來做到這一點?

+1

這正是你在做什麼,是什麼問題? – Nicolas

+0

當第一個條件1爲false時,它跳轉到evt.preventDefault()行。在調用evt.preventDefault()之前,我需要調用所有四個條件。 – haeminish

+0

這是因爲AND運算符在第一次錯誤後關閉。你需要一個OR運算符。 – Nicolas

回答

3

嘗試的邏輯運算||這是OR

1

如果條件至少有一個是假,它不會在IF塊中去。對於多個& &語句,一旦收到FALSE,將不再檢查所有其他成功的& &語句並返回FALSE。

0

它被稱爲短路。

1-在由& &組成的條件檢查中,如果第一個元素的計算結果爲false,則將忽略所有其餘條件,併爲整個條件返回false。

2-在由||組成的條件檢查中,如果第一個元素的計算結果爲true,則忽略所有其餘條件,並在整個條件下返回true。


他編輯了這個問題。這是不正確的。我正在讓它成爲社區wiki,留在這裏。

對此的最佳解決方法是使用||或在您的條件檢查中重新排序子條件的順序以便讓其他元素隨時得到測試。

1

如果

必須調用函數checkEmpty()爲每一個條件。

而且

我想打電話給evt.preventDefault()當所有的條件返回true。

如果您確信checkEmpty()返回一個布爾值,你可以使用bitwise and (&)操作:

function checkEmpty(x) { 
    console.log('checkEmpty called for ' + x); 

    return false; 
} 
if(checkEmpty('..1', '....') & //condition 1 
    checkEmpty('..2', '....') & //condition 2 
    checkEmpty('..3', '....') & //condition 3 
    checkEmpty('..4', '....')){ //condition 4 
    console.log('inside if'); 
} 

輸出:

checkEmpty called for ..1 
checkEmpty called for ..2 
checkEmpty called for ..3 
checkEmpty called for ..4 

fiddle demo here

+0

注意:如果'checkEmpty()'可能返回'true'或'false'以外的其他內容,請不要使用'&',因爲它是一個按位運算符。例如:'1&10'返回'0',如果它是一個邏輯運算符(這是因爲'truthy && truthy'是'true'),這不是你所期望的。 – acdcjunior

+0

OTOH,如果你不知道'checkEmpty()總是返回一個布爾值,你可以加倍否定它們:'if(!! checkEmpty('.. 1','....')&!! checkEmpty ('。2','....')...'(注意在每次'checkEmpty()'調用之前添加'!!')。 – acdcjunior

0

你現在在做什麼與鏈&&運營商說如果所有這些事情都是真的,那麼event.preventDefault。如果你真的需要檢查每一個條件,並且如果有的話是真的,那麼你應該使用邏輯OR運營商||來代替。

0

假設你有一個對象數組,你可以嘗試every函數。

var array = []; 
 

 
for (var i = 0; i < 4; i++) 
 
{ 
 
    array.push({ 
 
    id: i, bool: true 
 
    }); 
 
} 
 

 
function check(item) 
 
{ 
 
    return item.bool == true || false; 
 
} 
 

 
if (array.every(check)) 
 
{ 
 
    console.log("all true"); 
 
} 
 
else 
 
{ 
 
    console.log("return false instead"); 
 
} 
 

 

 

 
// Just an example of something that is false 
 
array[1].bool = false; 
 

 
if (!array.every(check)) 
 
{ 
 
    console.log("something is false"); 
 
}