使用对象而不是布尔值更改应用程序流

问题描述

我正在阅读《面向Web开发人员的专业Javascript》一书,当作者说:

时,我不理解这一部分。

错误地使用对象而不是对象 布尔值可以极大地改变您的应用程序流程。”

enter image description here

任何人都可以用一个例子来进一步解释它...谢谢

解决方法

它称为自动类型强制。在评估表达式时,JS会自动将变量强制为可以评估的类型。作者的意思是,如果在布尔评估中使用对象,则该对象强制转换为布尔类型-始终为true。

请参见以下代码段:

//An empty object
let o = {};

if (o)
  console.log(true)
else
  console.log(false);
  
  
 //Let's give it a value 
 o.status = false;
 
 if (o)
  console.log(true)
else
  console.log(false);

以上代码的结果为true true。这是由于以下事实:一个空对象将被强制为真实值-不管该对象具有什么虚假值,该对象仍将其评估为true。

,

主要是警告您不要对可能轻易“意外”返回true的对象执行等效运算符:

 public class AttendanceModel
    {
        public int userId { get; set; }

        [Display(Name = "Login As")]
        public string loginUser { get; set; }

        [Display(Name = "Name")]
        public string userName { get; set; }

        [Display(Name = "Password")]
        public string password { get; set; }
        public bool isActive { get; set; }

        [Display(Name = "Email")]
        public string email { get; set; }

        public enum LoginUser
        {
            Admin,Teacher,Student
        }
  
  }