JavaScript 判断 JSON 是否存在某字段可以吗? 答案是: 可以. 下面本篇文章给大家介绍一下 JavaScript 判断 JSON 是否存在某字段的方法. 有一定的参考价值, 有需要的朋友可以参考一下, 希望对大家有所帮助.
JavaScript 判断 JSON 是否存在某字段的方法
方式一 !("key" in obj)
方式二 obj.hasOwnProperty("key") //obj 为 JSON 对象.
例如:
- var jsonworld_pose = JSON.parse(data[0].world_pose);
- var jsonorientation = jsonworld_pose.orientation; // 次处可能为 undefined
- var jsonposition = jsonworld_pose.position;// 次处可能为 undefined
- if (jsonworld_pose.hasOwnProperty("orientation")) {
- // 使用时先进行判断
- $("#orientation-w").html(jsonorientation.w);
- $("#orientation-x").HTML(jsonorientation.x);
- $("#orientation-y").HTML(jsonorientation.y);
- $("#orientation-z").HTML(jsonorientation.z);
- }
- if (jsonworld_pose.hasOwnProperty("position")) {
- $("#position-x").HTML(jsonposition.x);
- $("#position-y").HTML(jsonposition.y);
- $("#position-z").HTML(jsonposition.z);
- }
更多 web 开发 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/qa/javascript/17308.html