为什么null在JavaScript中被认为是一个对象?

正在检查

if ( object == null )
      Do something

if ( !object )
      Do something

?

还有:

null和undefined之间的区别是什么?


当前回答

一些精度:

Null和undefined是两个不同的值。一个表示没有名称的值,另一个表示没有名称。


对于if(o), if中发生的事情如下所示:

括号o中的表达式被求值,然后if语句开始对括号中的表达式的值进行类型强制——在我们的例子中是o。

JavaScript中的Falsy(将被强制为false)值为:",null, undefined, 0和false。

其他回答

一些精度:

Null和undefined是两个不同的值。一个表示没有名称的值,另一个表示没有名称。


对于if(o), if中发生的事情如下所示:

括号o中的表达式被求值,然后if语句开始对括号中的表达式的值进行类型强制——在我们的例子中是o。

JavaScript中的Falsy(将被强制为false)值为:",null, undefined, 0和false。

Null和undefined对于值相等都是false (Null ==undefined):它们都崩溃为布尔值false。它们不是同一个对象(null!==undefined)。

Undefined是全局对象(浏览器中的“window”)的一个属性,但它是一个基本类型,而不是对象本身。它是未初始化的变量和函数的默认值,没有返回语句。

null是Object的一个实例。null用于返回集合对象以指示空结果的DOM方法,该方法提供false值而不指示错误。

null和undefined的主要区别在于null表示 一个缺失的对象,而undefined表示变量的未初始化状态。

你可以认为null是一个未定义的对象,但未定义只是未定义的 因为它的类型没有定义。

let a; 
console.log(a); //undefined, since it is declared but not initialized

console.log(null == undefined) //true
console.log(null === undefined) // false

console.log(typeof null) //object
console.log(typeof undefined) //undefined

思考“null”的最佳方式是回忆一下类似的概念是如何在数据库中使用的,在数据库中它表示字段包含“根本没有值”。

是的,物品的价值是已知的;它是“被定义的”。已经初始化。 该项的值是:“没有值。”

This is a very useful technique for writing programs that are more-easily debugged. An 'undefined' variable might be the result of a bug ... (how would you know?) ... but if the variable contains the value 'null,' you know that "someone, somewhere in this program, set it to 'null.'" Therefore, I suggest that, when you need to get rid of the value of a variable, don't "delete" ... set it to 'null.' The old value will be orphaned and soon will be garbage-collected; the new value is, "there is no value (now)." In both cases, the variable's state is certain: "it obviously, deliberately, got that way."

看看这个:

   <script>
function f(a){
  alert(typeof(a));
  if (a==null) alert('null');
  a?alert(true):alert(false);
}
</script>
                                          //return:
<button onclick="f()">nothing</button>    //undefined    null    false
<button onclick="f(null)">null</button>   //object       null    false
<button onclick="f('')">empty</button>    //string               false
<button onclick="f(0)">zero</button>      //number               false
<button onclick="f(1)">int</button>       //number               true
<button onclick="f('x')">str</button>     //string               true