如果循环中至少有一个元素返回false,如何将变量设置为false?

时间:2016-04-22 02:27:03

标签: javascript

以下函数循环访问对象的值。如果该值为空,则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.hasInvalidValuefalse设置为false。只有当所有值都不为空时才到true

1 个答案:

答案 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;
    }
  }
}