2013-07-17 33 views
2

JavaScripts typeof表达式检查null吗?JavaScript的typeof函数检查为null

var test = {}; 
console.log(typeof test['test']);//"undefined" 

var test = null; 
console.log(typeof test['test']);//TypeError: test is null 

显然,但为什么错误,如果typeof null是一个对象?

编辑:
我知道如何避免错误的类型,以及null没有属性,但我不知道是那里的typeof的行为作出解释。

+0

,因为第一个测试是空 – karaxuna

+1

'null'已经没有“测试”成员,试图访问它是非法的 –

+3

的问题是你正在尝试读取'null ['test']的值' – goat

回答

5
var test = { test: null }; 
console.log(typeof test['test']);// will be object 

你的代码抛出异常,因为你正在读空的属性是这样的:

null['test'] 
+0

事实上,你可以有一条只是说:“test ['test'];” (没有实际的值),它仍然会抛出错误。 – Katana314

1

的问题是,您要访问的test的元素,但testnull,而不是一个数组/目的。所以下面的代码会抛出一个错误:test['test']

如果您直接通过nulltypeof会正常工作。例如,使用Node.js的控制台:

> typeof null 
'object' 
0

你问它读取空这是没有意义的财产“测试”,误差基本上是告诉你,“测试为空 - >不能读取null属性“测试”。

你应该只是在做typeof test而不是typeof test['test'],我不确定你为什么要这么做。

0

你可以试试你测试作为

typeof (test && test['test']) 

这样你避免类型错误