JS中如何判断传过来的JSON数据中是否存在某字段
作者:bea
如何判断传过来的JSON数据中,某个字段是否存在, 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 testin
如何判断传过来的JSON数据中,某个字段是否存在,
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:
"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
有用 | 无用
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:
"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
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- js 动态修改css文件用到了cssRule
- jquery实现在页面加载的时自动为日期插件添加当前日期
- js匿名函数的调用示例(形式多种多样)
- javascript对中文按照拼音排序代码
- JS辨别访问浏览器判断是android还是ios系统
- JS中实现简单Formatter函数示例代码
- 用JavaScript实现使用鼠标画线的示例代码
- [原创]推荐10款最热门jQuery UI框架
- js选择并转移导航菜单示例代码
- js遍历子节点子元素附属性及方法
- jQuery实现返回顶部功能适合不支持js的浏览器
- 用循环或if语句从json中取数据示例
- 通过jquery 获取URL参数并进行转码
- 浅谈JavaScript中定义变量时有无var声明的区别
- [将免费进行到底]在Amazon的一年免费服务器上安装Node.JS, NPM和OurJS博客
- 使用node.js半年来总结的 10 条经验
- 推荐 21 款优秀的高性能 Node.js 开发框架
- 根据当前时间在jsp页面上显示上午或下午
- JQuery中使用Ajax赋值给全局变量失败异常的解决方法