天天看點

JavaScript 檢查一個 JSON 對象中是否對存指這下的 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? 

實際上,測試未定義這種結果确實不是一個比較精确的檢測鍵是否存在的有效方法。

false, but the key exists! 

上面的結果是 false ,但這個鍵确是存在的。

You should instead use the in operator: 

你應該換用 in 操作:

true, regardless of the actual value 

結果是 true,不考慮實際值

If you want to check if a key doesn't exist, remember to use parenthesis: 

如果你想要檢查一個鍵是否不存在,記得使用取反:

true if "key" doesn't exist in object 

如果鍵存在于這個對象裡,那麼結果是 true

ERROR! Equivalent to "false in obj" 

這個有錯!等于 "false in obj" 

Or, if you want to particularly test for properties of the object instance (and not inherited properties), use hasOwnProperty: 

或者,如jusi你特别想檢測一下對象實際的屬性(并非繼承的屬性),那麼使用 hasOwnProperty:

true

這個測試的結果是 true

繼續閱讀