2013-09-25 23 views
3

我有這樣的代碼:令人費解遺漏的類型錯誤:Object.keys呼籲非對象

if(typeof x == 'object') 
    return "{"+Object.keys(x)+"}"; 

它導致(鉻):

Uncaught TypeError: Object.keys called on non-object 

誰能告訴我這是怎麼回事?順便說一句:Firefox也是這樣。

ps:不知道對象是什麼。 Firefox調試失敗了我。

+0

也許答案就在這裏:http://stackoverflow.com/questions/17319336/uncaught -typeerror-object-keys-called-on-non-object-while-trying-to-access-obje – Robbert

+5

什麼是'x'?也許它是'空'? –

+0

'x' null? typeof將返回'object'爲空值 – EkoostikMartin

回答

7

x很可能是null(這是一個對象)。你應該明確地if(typeof x === 'object' && x !== null)

漫步在規範檢查(解釋邏輯):

Object.keyshttp://www.ecma-international.org/ecma-262/5.1/#sec-15.2.3.14讀取

If the Type(O) is not Object, throw a TypeError exception.

TypeNullnullhttp://www.ecma-international.org/ecma-262/5.1/#sec-8.2

typeofhttp://www.ecma-international.org/ecma-262/5.1/#sec-11.4.3

該表顯示,typeof null其實"object"

所以其實null滿足typeof x === "object"並觸發TypeError例外

相關問題