2013-07-17 36 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']) 

這樣你避免類型錯誤