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

正在检查

if ( object == null )
      Do something

if ( !object )
      Do something

?

还有:

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


当前回答

下面的函数说明了原因,并能够计算出差异:

function test() {
        var myObj = {};
        console.log(myObj.myProperty);
        myObj.myProperty = null;
        console.log(myObj.myProperty);
}

如果你打电话

test();

你要

未定义的 零

第一个console.log(…)尝试在myObj尚未定义时从myProperty获取myProperty -因此它返回“未定义”。在将其赋值为null后,第二个console.log(…)显然返回“null”,因为myProperty存在,但它的值为null。

为了能够查询这种差异,JavaScript有null和undefined:而null就像在其他语言中是一个对象一样,undefined不能是一个对象,因为没有可用的实例(甚至不是空实例)。

其他回答

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

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

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

差异可以总结为以下代码片段:

alert(typeof(null));      // object
alert(typeof(undefined)); // undefined

alert(null !== undefined) //true
alert(null == undefined)  //true

检查

Object == null与检查if (! Object)不同。

后者等于!布尔(对象),因为一元!运算符自动将右操作数转换为布尔型。

因为布尔(null)等于false,那么!false === true。

因此,如果对象不是null,而是false或0或"",检查将通过 因为:

alert(Boolean(null)) //false
alert(Boolean(0))    //false
alert(Boolean(""))   //false

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."

JavaScript中许多不同的null检查的比较:

http://jsfiddle.net/aaronhoffman/DdRHB/5/

// Variables to test
var myNull = null;
var myObject = {};
var myStringEmpty = "";
var myStringWhiteSpace = " ";
var myStringHello = "hello";
var myIntZero = 0;
var myIntOne = 1;
var myBoolTrue = true;
var myBoolFalse = false;
var myUndefined;

...trim...

http://aaron-hoffman.blogspot.com/2013/04/javascript-null-checking-undefined-and.html