以下函數循環對象的值。如果該值爲空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
我怎麼做,所以validate
套this.hasInvalidValue
到false
如果至少1值爲false
。如果所有的值都不是空的,只有true
?
只要您發現無效字段,您可以使用break;'語句來打破for循環,因爲不需要檢查其餘字段。 – scoots
什麼是'this.object'?請讓你的問題更清楚。 – PHPglue