【问题标题】:String Comparison does not work as intended [duplicate]字符串比较无法按预期工作[重复]
【发布时间】:2020-04-23 20:52:38
【问题描述】:

我正在开发一个连接到 firebase 的 Ionic Web 项目。

我从firestore中检索数据并使用它来确定用户是管理员还是基金经理,但字符串比较功能不起作用。

这是我的打字稿代码。

role: string = "";
  admin: boolean = false;
  fm: boolean = false;

  constructor(private authService: AuthService, private router: Router,) { }

  ngOnInit() {
    this.fname = "";
    this.lname = "";
    this.nric = "";
    this.role = "";
    this.admin = false;
    this.fm = false;
    this.user = this.authService.getCurrentUser();
    this.getProfile();
    if (this.role = "Admin") {
      console.log("Admin")
      this.admin = true;
    }
    else {
      if (this.role = "Fund Manager") {
        console.log("Fund Manager")
      }
    }

this.getProfile() 将填满this.role。当this.role"User" 时,Admin 变为 true,我不确定是什么导致了问题。

我的代码有什么问题吗?

【问题讨论】:

标签: javascript typescript


【解决方案1】:

您可以使用=====。但是===操作符(严格比较)不会自动转换类型,所以我觉得比较好:

if (this.role === "Admin") {
    // do something
}

补充:switch case语句也使用严格比较,值必须是相同类型才能匹配

switch (this.role) {
    case 'Admin':
        // do something
        break;
    case 'Manager':
        // do others
        break;
}

【讨论】:

  • 感谢您的帮助!我设法解决了这个问题!
【解决方案2】:

使用比较运算符== 而不是赋值运算符=

if (this.role == "Admin") {
  console.log("Admin")
  this.admin = true;
}
else {
  if (this.role == "Fund Manager") {
    console.log("Fund Manager")
  }

【讨论】:

    【解决方案3】:

    =不同于==(===)。形式是给一个变量赋值,后者是做自己想要的比较。所以这里this.role = 'admin'永远为真。

    【讨论】:

      【解决方案4】:

      要为变量分配任何值,请使用=。 要比较两个值而不考虑它们的数据类型,请使用== 要比较两个值以及变量数据类型,请使用===

      使用===== 比较两个变量

      if ( this.role == "Admin"){
      
         //your logic here
      
      }
      

      if ( this.role === "Admin"){
      
          //your logic here
      }
      

      【讨论】:

        【解决方案5】:

        你没有比较,你在分配一个价值。 除了已经给出的答案:您可以使用YODA Condition 样式来避免这样的错误。如果您编写像if( "Admin" = this.role) 这样的代码会自动导致错误,该错误将显示在浏览器的控制台中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-26
          • 1970-01-01
          • 2023-02-05
          • 2023-04-03
          • 1970-01-01
          • 2019-01-28
          相关资源
          最近更新 更多