赋予变量的赋值之间的差异?

5 javascript null undefined

  1. 0
  2. 空值
  3. 未定义
  4. 空字符串

我使用它们,但我仍然没有意识到上面列表中每个潜在客户的边际差异.我大多使用0,false.但是我遇到过许多使用未定义的空字符串的脚本.我想知道它们之间的确切差异.我知道这是一个愚蠢的问题,但如果我得到一个简短的答案就会很棒.

Pau*_*aul 0

类型就是区别。

false是布尔值、0是数字、null是对象、undefined未定义、''是字符串。

您可以根据用途来选择类型。例如:

// There is nothing wrong with this block of code
var num_cats = 7;
if(num_cats){
    // num_cats is truthy
}

// This block works but it could be made more clear
var has_cat = num_cats;
if(has_cat){
    // This would work, but it doesn't make sense. As a developer I would
    // expect that has_cat should be either true or false, not 7. 
    // One way to convert the number to a boolean would be:
        has_cat = !!num_cats 
}
Run Code Online (Sandbox Code Playgroud)

两个最令人困惑的错误值可能是nullundefined

null基本上意味着该变量存在,但其值未知。 undefined意味着该变量不存在(尽管可以将变量显式设置为未定义var x = undefined;,然后该变量x存在但显式未定义,这意味着您可以将其视为不存在。