This article mainly introduces how to determine whether JSON data has a field in Javascript. If you need it, you can refer to how to determine whether a field exists in the transmitted JSON data,
1. obj ["key"]! = Undefined
This is flawed. If the key is defined and the value of 2 is undefined, a problem will occur.
2 .! ("Key" in obj)
3. obj. hasOwnProperty ("key ")
The two methods are better. We recommend that you use them.
Original answer:
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 shoshould 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 maid test for properties of the object instance (and not inherited properties), usehasOwnProperty:
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.