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

正在检查

if ( object == null )
      Do something

if ( !object )
      Do something

?

还有:

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


当前回答

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

其他回答

为了补充“undefined和null之间的区别是什么”的答案,请参阅JavaScript权威指南第6版,本页第41页:

你可能认为undefined表示系统级的,意外的, 或者类似错误的无值和null表示程序级, 正常的,或预期的价值缺失。如果你需要分配一个 将这些值传递给变量或属性或将其中一个值传递给 一个函数,null几乎总是正确的选择。

什么是类型?

类型是对值进行分类的一种方式。下面是一个包含有问题的类型及其typeof结果的表格。

Type Values type contains typeof result Is typeof result a lie?
Undefined Only: undefined "undefined" No
Null Only: null "object" Yes
Object Infinite amount of values: {}, {a: "b"}, ... "object" No

null不是一个对象,它是一个null类型的值。

typeof操作符在说谎!它返回“object”为空在JavaScript语言中是一个错误。

我在我的开源电子书中写了一章。你可以在这里阅读https://github.com/carltheperson/advanced-js-objects

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

没有定义的属性是未定义的。null是一个对象。它的类型是object。Null是一个特殊值,表示“没有值”。Undefined不是一个对象,它的类型是Undefined。

你可以声明一个变量,将其设置为null,除了你会看到“null”和“undefined”打印出来之外,行为是相同的。你甚至可以将一个未定义的变量与null进行比较,反之亦然,条件将为真:

 undefined == null
 null == undefined

更多细节请参考JavaScript null和undefined之间的差异。

还有你的新编辑,是的

if (object == null)  does mean the same  if(!object)

当测试object是否为false时,它们都只满足测试是否为false时的条件,而不满足测试是否为true时的条件

检查这里:Javascript抓住你了

Null是一个对象。它的类型是null。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."