可能是一个非常基本的问题来自困惑的javascript noob ......
为什么
var hasthisvalue = null;
if (hasthisvalue)
print("hasthisvalue hs value");
和
var hasthatvalue = "";
if (hasthatvalue)
print("hasthatvalue has value");
不要打印任何内容,但如果我将这两个结合起来
var combined = "hasthisvalue" + "hasthatvalue";
if (combined)
print ("combined has value");
它呢?
或更直接:
var combined = null + "";
if (combined)
print ("combined has value");
如果我只添加两个没有值的变量,为什么“combined”有一个值?我错过了什么?
答案 0 :(得分:3)
当您单独比较它们时,每个都会转换为false
检查中的if
。合并它们后,null
将成为字符串"null"
,因此它们的串联是字符串"null"
,不会转换为false
答案 1 :(得分:2)
前两个示例是值“falsy”的情况。在松散比较期间,这些值等于false
:
此列表中不包含的其他值“truthy”,在松散比较上等于true
。
第三种情况,您可以在控制台中尝试。 null+''
成为一个字符串:"null"
,因此非常真实。