if (!this.realName)和 if (this.realName === "" || this.realName=== null || this.realName ===undefined) 区别在哪里,哪种写法更好?
这两个if
语句检查this.realName
的不同条件,并因此有不同的行为。
-
if (!this.realName)
:
这个语句检查this.realName
是否存在一个“假值”(falsy value)。在JavaScript中,以下值被认为是假值:false
0
(数字零)""
(空字符串)null
undefined
NaN
(非数字值)所以,如果this.realName
是上述任何一个值,!this.realName
都会返回true
。这意味着这个检查不仅仅检查this.realName
是否为空字符串、null
或undefined
,还检查它是否为数字零、false
或NaN
。
-
if (this.realName === "" || this.realName === null || this.realName === undefined)
:
这个语句明确地检查this.realName
是否为空字符串、null
或undefined
。它不会对其他假值(如0
、false
或NaN
)做出反应。
哪种写法更好?
这取决于你的具体需求。
- 如果你只想检查
this.realName
是否为空字符串、null
或undefined
,并且不关心其他假值,那么第二种写法更明确,也更好。 - 如果你想要一个更广泛的检查,包括其他假值,那么第一种写法可能更适合你。
然而,通常来说,明确性更好,因为它减少了代码阅读者和维护者需要猜测的部分。因此,如果你只是想检查空字符串、null
和undefined
,第二种写法可能是更好的选择。但请确保你的代码逻辑确实只需要这些特定的检查。