【问题标题】:Chaining If conditions with && operator使用 && 运算符链接 If 条件
【发布时间】:2022-08-02 18:38:28
【问题描述】:

我有以下代码 - 它执行各种状态检查:

CheckValStates= () => {

  _stateCheck = val => {
    if (!val || val == \'\' ) {
      return true;
    }
    return false;
  };


if (
      this._stateCheck(this.state.arReason) ||
      this._stateCheck(this.state.handoverType) ||
      (this.state.handoverType === \'CUSTOMER\' &&
        this._stateCheck(this.state.staffHandoverDeets)) ||
      (this.state.handoverType === \'GUARD\' &&
        this._stateCheck(this.state.keyStatus) &&
        this._stateCheck(this.state.staticOfficerHandover))
    ) {
     return true;
    }

  return false;
  };
}

我遇到了以下行的问题:

(this.state.handoverType === \'GUARD\' &&
        this._stateCheck(this.state.keyStatus) &&
        this._stateCheck(this.state.staticOfficerHandover))
)

如果只有前 2 个元素为真,则返回真 - 第三次检查 (this._stateCheck(this.state.staticOfficerHandover)) 被忽略。我期待所有三个检查都匹配一个真实的结果。

如果我用 - 替换那个链接的语句

if (


      this._stateCheck(this.state.arReason) ||
      this._stateCheck(this.state.handoverType) ||
      (this.state.handoverType === \'CUSTOMER\' &&
        this._stateCheck(this.state.staffHandoverDeets)) ||

      (this.state.handoverType === \'GUARD\' && this._stateCheck(this.state.keyStatus) || this.state.handoverType === \'GUARD\' && this._stateCheck(this.state.staticOfficerHandover) )
    ) 

它按预期执行检查。我想知道为什么。

  • 这意味着 && 运算符存在问题,这是不太可能的。你怎么知道第三个操作数没有被计算?和/或条件导致true
  • 您可以在_stateCheck 中添加console.log(val)

标签: javascript reactjs


【解决方案1】:

我认为您的功能 _stateCheck 并不完美:某些值可能会导致问题。

stateCheck(null) // true
stateCheck(undefined) // true
stateCheck("") // true
stateCheck({}) // false
stateCheck([]) // true  - possible problem
stateCheck(true) // false
stateCheck(false) // true - possible problem
stateCheck(0) // true - possible problem
stateCheck(-10) // false
stateCheck(10) // false

this.state.staticOfficerHandover 是一个有问题的值,stateCheck 将发送 true

例子:

const stateCheck = val => {
    if (!val || val == '' ) {
      return true;
    }
    return false;
  };


const state = {
    handoverType: "GUARD",
    keyStatus : "",
    staticOfficerHandover: true,
}

const condition = (state.handoverType === 'GUARD' &&
 stateCheck(state.keyStatus) &&
 stateCheck(state.staticOfficerHandover)
 )
console.log(condition); // false

state.staticOfficerHandover = false;
const condition2 = (state.handoverType === 'GUARD' &&
 stateCheck(state.keyStatus) &&
 stateCheck(state.staticOfficerHandover)
 )
 console.log(condition2); // true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 2014-12-11
    • 2019-10-20
    • 2023-03-03
    • 2022-01-07
    • 2017-03-21
    • 1970-01-01
    相关资源
    最近更新 更多