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

How to set a variable to false if at least one element in a loop returns false?

本文关键字:false 变量 设置 返回 循环 元素 有一个 如果      更新时间:2023-09-26

以下函数循环访问对象的值。如果值为空this.hasInvalidValue设置为 true ,如果值不为空,则设置为 false this.hasInvalidValue

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如果至少false 1 个值,this.hasInvalidValue设置为 false.并且仅在所有值都不为空时才true

这个怎么样?

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