close

轉自 https://stackoverflow.com/questions/455338/how-do-i-check-if-an-object-has-a-key-in-javascript

--

Ans: 使用in運算子

Try the JavaScript in operator.

 

if ('key' in myObj)

 

And the inverse.

 

if (!('key' in myObj))

 

Be careful! The in operator matches all object keys, including those in the object's prototype chain.

Use myObj.hasOwnProperty('key') to check an object's own keys and will only return true if key is available on myObj directly:

 

myObj.hasOwnProperty('key')

 

Unless you have a specific reason to use the in operator, using myObj.hasOwnProperty('key') produces the result most code is looking for.

--

全站熱搜
創作者介紹
創作者 dizzy03 的頭像
dizzy03

碎碎念

dizzy03 發表在 痞客邦 留言(0) 人氣()