为什么null在JavaScript中被认为是一个对象?
正在检查
if ( object == null )
Do something
和
if ( !object )
Do something
?
还有:
null和undefined之间的区别是什么?
为什么null在JavaScript中被认为是一个对象?
正在检查
if ( object == null )
Do something
和
if ( !object )
Do something
?
还有:
null和undefined之间的区别是什么?
当前回答
例如窗口。someWeirdProperty是未定义的
”窗口。someWeirdProperty === null"的值为false时
”窗口。someWeirdProperty === undefined"的值为true。
此外,checkif if (!o)与检查if (o == null)是否为假并不相同。
其他回答
思考“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."
什么是类型?
类型是对值进行分类的一种方式。下面是一个包含有问题的类型及其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是两个不同的值。一个表示没有名称的值,另一个表示没有名称。
对于if(o), if中发生的事情如下所示:
括号o中的表达式被求值,然后if语句开始对括号中的表达式的值进行类型强制——在我们的例子中是o。
JavaScript中的Falsy(将被强制为false)值为:",null, undefined, 0和false。
下面的函数说明了原因,并能够计算出差异:
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不能是一个对象,因为没有可用的实例(甚至不是空实例)。
typeof null; // object
typeof undefined; // undefined
null值表示有意不存在任何对象值。它是JavaScript的基本值之一,在布尔操作中被视为假值。
var x = null;
var y;
X被声明并定义为null
Y声明了,但没有定义。它声明时没有值,所以没有定义。
Z没有被声明,所以如果你试图使用Z,它也是未定义的。