wns9778.com_威尼斯wns.9778官网

热门关键词: wns9778.com,威尼斯wns.9778官网
wns9778.com > 计算机教程 > JS中如何判断传过来的JSON数据中是否存在某字段

原标题:JS中如何判断传过来的JSON数据中是否存在某字段

浏览次数:100 时间:2019-09-11

如何判断传过来的JSON数据中,某个字段是否存在,

如何判断传过来的JSON数据中,某个字段是否存在,

1.obj["key"] != undefined
这种有缺陷,如果这个key定义了,并且就是很2的赋值为undefined,那么这句就会出问题了。
2.!("key" in obj)
3.obj.hasOwnProperty("key")

1.obj["key"] != undefined

这两种方法就比较好了,推荐使用。

这种有缺陷,如果这个key定义了,并且就是很2的赋值为undefined,那么这句就会出问题了。

答案原文:

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:

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?

"key" in obj // true, regardless of the actual value

var obj = { key: undefined };
obj["key"] != undefined // false, but the key exists!

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

You should instead use the in operator:

!("key" in obj) // true if "key" doesn't exist in object
wns9778.com,!"key" in obj // ERROR! Equivalent to "false in obj"

"key" in obj // true, regardless of the actual value

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

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

本文由wns9778.com发布于计算机教程,转载请注明出处:JS中如何判断传过来的JSON数据中是否存在某字段

关键词: wns9778.com

上一篇:jQuery插件编写步骤详解

下一篇:没有了