gpt4 book ai didi

javascript - 用于检测不存在对象中的 JSON 属性的函数

转载 作者:行者123 更新时间:2023-11-29 16:58:00 25 4
gpt4 key购买 nike

有没有一种方法可以在不提供特定对象的情况下检查 JSON 中是否存在属性?

例如,

data.programs.text.background

backgroundtext 的属性。但是,如果当前对象中不存在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com