以下函数循环访问对象的值。如果该值为空,则this.hasInvalidValue
设置为true
,如果该值为空,则this.hasInvalidValue
设置为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
如果至少有1个值validate
,我该如何才能this.hasInvalidValue
将false
设置为false
。只有当所有值都不为空时才到true
?
答案 0 :(得分: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;
}
}
}