有没有办法在不提供特定对象的情况下检查 JSON 中是否存在属性?
例如,
data.programs.text.background
background
是text
的属性。但是如果当前对象中不存在 text
对象怎么办?
JSON:
{
"programs": [
{
"width": 500,
"height": 600,
"text": {
"foreground": "black",
"background": "white"
}
},
{
"width": 100,
"height": 200
},
{
"width": 800,
"height": 300,
"text": {
"foreground": "yellow",
"background": "red"
}
}
]
}
控制台会给出错误 Uncaught TypeError: Cannot read property 'background' of undefined
测试 data.programs.text.background == undefined
不起作用。
是否可以编写一个函数,通过简单地提供对对象属性(例如 data.programs.text.background
)的引用来检测对象是否存在以及属性是否存在?
最佳答案
您可以使用.hasOwnProperty()
判断一个对象是否具有该对象的属性。
关于javascript - 用于检测不存在对象中的 JSON 属性的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30787311/