gpt4 book ai didi

javascript - 如何避免在没有值的对象键中未定义?

转载 作者:行者123 更新时间:2023-11-29 14:45:39 24 4
gpt4 key购买 nike

我正在尝试像这样迭代一个对象:

0: Object
appointments: Array[2]
unavailables: Array[2]
0: Object
1: Object
book_datetime: "2015-10-22 02:46:23"
data: "0"
end_datetime: "2015-10-22 13:00:00"
hash: null
id: "21"
id_google_calendar: null
id_services: null
id_users_customer: null
id_users_provider: "87"
is_unavailable: "1"
notes: "Nessuna"
resource_id: "0"
start_datetime: "2015-10-22 12:00:00"
__proto__: Object
length: 2
__proto__: Array[0]
__proto__: Object
1: Object
appointments: Array[1]
unavailables: Array[0]
length: 0
__proto__: Array[0]
__proto__: Object
length: 2
__proto__: Array[0]

这样:

$.each(response, function(_, obj) 
{
$.each(obj, function(key, val)
{
if (key === 'unavailables')
{
console.log("=> ", val[0]['id']);
}
});
});

现在一切正常,但您如何看到第二个数组包含 unavailables length = 0 ,当循环在这里时,我得到

Cannot read property 'id' of undefined

如何避免这种情况?有没有一种方法可以检查当前键是否包含值?

最佳答案

在访问 val 之前,我可能会再做一次检查:

if (key === 'unavailables' && val && val.length) 
{
console.log("=> ", val[0]['id']);
}

关于javascript - 如何避免在没有值的对象键中未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33280276/

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