JS中如何判斷傳過來的JSON數(shù)據(jù)中是否存在某字段
如何判斷傳過來的JSON數(shù)據(jù)中,某個(gè)字段是否存在,
1.obj["key"] != undefined
這種有缺陷,如果這個(gè)key定義了,并且就是很2的賦值為undefined,那么這句就會(huì)出問題了。
2.!("key" in obj)
3.obj.hasOwnProperty("key")
這兩種方法就比較好了,推薦使用。
答案原文:
Actually, checking for undefined-ness is not an accurate way of testing whether a key exists. What if the key exists but the value is actually undefined?
var obj = { key: undefined };
obj["key"] != undefined // false, but the key exists!
You should instead use the in operator:
"key" in obj // true, regardless of the actual value
If you want to check if a key doesn't exist, remember to use parenthesis:
!("key" in obj) // true if "key" doesn't exist in object
!"key" in obj // ERROR! Equivalent to "false in obj"
Or, if you want to particularly test for properties of the object instance (and not inherited properties), usehasOwnProperty:
obj.hasOwnProperty("key") // true
相關(guān)文章
canvas基礎(chǔ)繪制-絢麗倒計(jì)時(shí)的實(shí)例
下面小編就為大家?guī)硪黄猚anvas基礎(chǔ)繪制-絢麗倒計(jì)時(shí)的實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-09-09探究JavaScript原型數(shù)據(jù)共享與方法共享實(shí)現(xiàn)
這篇文章主要介紹了探究JavaScript原型數(shù)據(jù)共享與方法共享實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05微信小程序基于高德地圖API實(shí)現(xiàn)天氣組件(動(dòng)態(tài)效果)
這篇文章主要介紹了微信小程序基于高德地圖API實(shí)現(xiàn)天氣組件(動(dòng)態(tài)效果),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10javascript實(shí)現(xiàn)復(fù)制與粘貼操作實(shí)例
這篇文章主要介紹了javascript實(shí)現(xiàn)復(fù)制與粘貼操作,以實(shí)例形式講述了javascript實(shí)現(xiàn)復(fù)制與粘貼操作的實(shí)現(xiàn)方法,需要的朋友可以參考下2014-10-10微信小程序之?dāng)?shù)據(jù)緩存的實(shí)例詳解
這篇文章主要介紹了微信小程序之?dāng)?shù)據(jù)緩存的實(shí)例詳解的相關(guān)資料,希望通過本文能幫助到大家,讓大家掌握這部分內(nèi)容,需要的朋友可以參考下2017-09-09基于JavaScript實(shí)現(xiàn)網(wǎng)頁計(jì)算器
這篇文章主要為大家詳細(xì)介紹了基于JavaScript實(shí)現(xiàn)網(wǎng)頁計(jì)算器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-05-05