2016-04-22 19 views
0

以下函數循環對象的值。如果該值爲空this.hasInvalidValue設置爲true,如果它不是空this.hasInvalidValue設置爲false如果循環中至少有一個元素返回false,如何將變量設置爲false?

user: { 
    email: '', 
    password: '' 
} 

function validate() { 
    for (let key in this.object) { 
    const isValueInvalid = !this.object[key] 
    if (this.isKeyRequired(key) && isValueInvalid) { 
     this.hasInvalidValue = true 
    } 
    if (this.isKeyRequired(key) && !isValueInvalid) { 
     this.hasInvalidValue = false 
    } 
    } 
} 

有一個問題與此有關。考慮一個登錄表單:

Email // empty (this.hasInvalidValue is set to false) 
Password // not empty (this.hasInvalidValue is set to true) 

// Final value of this.hasInvalidValue is true. Good 

Email // not empty (this.hasInvalidValue is set to false) 
Password // empty (this.hasInvalidValue is set to true) 

// Final value of this.hasInvalidValue is false. Not good 

我怎麼做,所以validatethis.hasInvalidValuefalse如果至少1值爲false。如果所有的值都不是空的,只有true

+0

只要您發現無效字段,您可以使用break;'語句來打破for循環,因爲不需要檢查其餘字段。 – scoots

+0

什麼是'this.object'?請讓你的問題更清楚。 – PHPglue

回答

2

這個怎麼樣?

function validate() { 
    this.hasInvalidValue = true 
    for (let key in this.object) { 
    const isKeyInvalid = !this.object[key] 
    if (this.isKeyRequired(key) && !isKeyInvalid) { 
     this.hasInvalidValue = false 
     break; 
    } 
    } 
} 
+0

除了OP不希望'validate()'返回'true'或'false',他希望將'this.hasInvalidValue'設置爲'true'或'false'外,其他都是正確的。 – RJM

+0

@RJM謝謝!代碼編輯。 –

相關問題