我有這樣的代碼:令人費解遺漏的類型錯誤:Object.keys呼籲非對象
if(typeof x == 'object')
return "{"+Object.keys(x)+"}";
它導致(鉻):
Uncaught TypeError: Object.keys called on non-object
誰能告訴我這是怎麼回事?順便說一句:Firefox也是這樣。
ps:不知道對象是什麼。 Firefox調試失敗了我。
我有這樣的代碼:令人費解遺漏的類型錯誤:Object.keys呼籲非對象
if(typeof x == 'object')
return "{"+Object.keys(x)+"}";
它導致(鉻):
Uncaught TypeError: Object.keys called on non-object
誰能告訴我這是怎麼回事?順便說一句:Firefox也是這樣。
ps:不知道對象是什麼。 Firefox調試失敗了我。
x
很可能是null
(這是一個對象)。你應該明確地if(typeof x === 'object' && x !== null)
漫步在規範檢查(解釋邏輯):
Object.keys
:http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.3.14讀取
If the Type(O) is not Object, throw a TypeError exception.
這Type
是Null
爲null
(http://www.ecma-international.org/ecma-262/5.1/#sec-8.2)
typeof
:http://www.ecma-international.org/ecma-262/5.1/#sec-11.4.3
該表顯示,typeof null
其實"object"
所以其實null
滿足typeof x === "object"
並觸發TypeError
例外
也許答案就在這裏:http://stackoverflow.com/questions/17319336/uncaught -typeerror-object-keys-called-on-non-object-while-trying-to-access-obje – Robbert
什麼是'x'?也許它是'空'? –
'x' null? typeof將返回'object'爲空值 – EkoostikMartin