0

可能是一个困惑的javascript菜鸟提出的一个非常基本的问题......

为什么

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");

如果我只添加两个没有值的变量,为什么“组合”有一个值?我错过了什么?

4

2 回答 2

3

当您分别比较它们时,每个都转换为false支票if。当你组合它们时,null变成了 string "null",所以它们的连接是 string "null",它不会转换为false

于 2012-05-27T11:54:35.940 回答
2

The first 2 examples are situations where the values are "falsy". These values are equal to false during a loose comparison:

  • null
  • undefined
  • blank string
  • boolean false
  • the number 0
  • NaN

Other values not in this list are "truthy" and are equal to true on a loose comparison.

The third case, you can try in the console. null+'' becomes a string: "null" and is therefore truthy.

于 2012-05-27T12:00:28.033 回答