【问题标题】:issues with === in typescript打字稿中 === 的问题
【发布时间】:2019-02-01 02:45:23
【问题描述】:

我有一个 if 块,如下所示:

if (this.totalTenants === 1) { this.newTenants.tenant2 = Object.assign({ name: null, number: null }, this.emptyTenant); this.newTenants.tenant3 = Object.assign({ name: null, number: null }, this.emptyTenant); this.newTenants.tenant4 = Object.assign({ name: null, number: null }, this.emptyTenant); this.newTenants.tenant2 = this.emptyTenant; this.newTenants.tenant3 = this.emptyTenant; this.newTenants.tenant4 = this.emptyTenant; this.newTenants.rentAmount = 3200; }

但是当 this.totalTenants 的值为 1 时,它不会进入 if 块。

我正在使用 typescript 开发 Angular 6。

如果我 if (this.totalTenants == 1) 双等号 ==

然后执行 if 块,但我收到如下所示的错误: [tslint] == 应该是 ===(三等号)

【问题讨论】:

  • 在 this.totalTenants 之前添加一个加号 (+),例如 if (+this.totalTenants === 1){....}
  • 添加console.log(this.totalTenants) 以确保totalTenants 是一个整数。

标签: if-statement angular6 typescript3.0


【解决方案1】:

===== 运算符的区别在于,第一个进行自动转换以方便比较,第二个不进行任何转换。

因此,如果您尝试比较两个数字值,但其中一个是数字的字符串表示形式,则使用 === 运算符比较失败。

您可能正在使用像 '1' 这样的字符串值,要检查这一点,您可以执行以下操作:

console.log(typeof this.totalTenants)

如果结果为字符串,则应将运算符更改为 == 或将该值转换为在变量前面加上 + 的数字,如下所示:

if (+this.totalTenants === 1) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 2023-03-31
    • 2016-06-18
    • 2019-07-09
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多