javascript - TypeError:无法读取未定义的属性“时间”
问题描述
我有类型错误。我的变量在使用 node.js 运行时创建了这个错误。我的变量在下面。如何正确描述我的变量?
let allDevices = {
1: {
time: []
},
2: {
time: []
},
3: {
time: []
}
}
解决方案
我猜您正在尝试allDevices.1.time
获取上述错误消息。使用数字对象键,您需要使用[]
而不是.
符号来引用编号的对象键:
let allDevices = {
1: {
time: []
},
2: {
time: []
},
3: {
time: []
}
}
console.log(allDevices[1].time) // or allDevices['1'].time
不过,您可能不想要那种对象结构;allDevices 可能应该只是一个数组,因此您不需要手动管理索引号。您可以以相同的方式访问它(但请注意,数组是零索引的):
let allDevices = [
{
time: []
},
{
time: []
},
{
time: []
}
]
console.log(allDevices[0].time) // here, allDevices['1'] would not work; the index must be a number
如果您已经在使用括号表示法但仍然出现“未定义”错误,请在尝试访问之前检查以确保数据存在;如果 allDevices 是由异步设置的,则您需要等到该异步调用返回。