【问题标题】:Operator < cannot be applied to types Number and boolean运算符 < 不能应用于 Number 和 boolean 类型
【发布时间】:2019-05-08 14:59:58
【问题描述】:

我有三个数字,我正在尝试比较其中一个是否包含在其他 2 中。

  let myMonthly = this.profile.expectedpayhourlystart + 
  this.profile.expectedpayhourlyend;
  myMonthly = ((((myMonthly/2)*8)*5)*4);
  let jobStart = item.monthlyPrice - 200;
  let jobEnd = item.monthlyPrice + 200;

  if( jobEnd < myMonthly < jobStart ){ <-- 'Operator < cannot be applied to boolean or number'

  }

为什么我会收到此错误?我应该改变什么?

【问题讨论】:

  • if (jobEnd &lt; myMonthly &amp;&amp; myMonthly &lt; jobStart)
  • 是的,这有帮助。将等待解释为什么这有效而那无效。
  • &lt;运算符是二元的,有两个操作数,问题是表达式被解析为:(jobEnd &lt; myMonthly) &lt; jobStart,第一个操作数(jobEnd &lt; myMonthly)得到一个布尔值,后面的运算符得到一个布尔值和一个数字。检查AST

标签: javascript typescript


【解决方案1】:
jobEnd < myMonthly

将评估为真或假。 所以如果你写:

if( jobEnd < myMonthly < jobStart)

它本质上是在尝试评估

if( true < jobStart )

这是将 ,因为 jobStart 是一个数字。

你需要这样写:

if( jobEnd < myMonthly && myMonthly < jobStart )

【讨论】:

    【解决方案2】:

    如果您像这样堆叠 jobEnd < myMonthly ,这会导致布尔值并将结果与​​ jobStart 进行比较,这是一个数字。用&amp;&amp;点赞

    if (jobEnd < myMonthly &&  myMonthly < jobStart)
    

    【讨论】:

      猜你喜欢
      • 2023-02-11
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 2020-04-28
      • 1970-01-01
      • 2022-11-12
      相关资源
      最近更新 更多