未捕获的类型错误:无法设置未定义的属性“索引”
Posted
技术标签:
【中文标题】未捕获的类型错误:无法设置未定义的属性“索引”【英文标题】:Uncaught TypeError: Cannot set property 'index' of undefined 【发布时间】:2021-10-04 18:28:47 【问题描述】:这是我想要做的:
interface VehicleSeatData
index: number;
positions: Vector3Mp;
interface VehicleSeat
[key: string]: VehicleSeatData;
getSeatData(vehicle: VehicleMp): VehicleSeat | null
if(!vehicle)
return null;
let seats: VehicleSeat = ;
seats['seat_r'].index = vehicle.getBoneIndexByName('seat_r');
seats['seat_pside_f'].index = vehicle.getBoneIndexByName('seat_pside_f');
seats['seat_r'].positions = vehicle.getWorldPositionOfBone(seats['seat_r'].index);
seats['seat_pside_f'].positions = vehicle.getWorldPositionOfBone(seats['seat_pside_f'].index);
return seats;
我得到的错误是:
Uncaught TypeError: Cannot set property 'index' of undefined
我不确定我哪里出错了,我读过的所有内容(到目前为止)都告诉我我的方向是正确的。这不可能吗?
【问题讨论】:
【参考方案1】:VehicleSeatData 没有任何属性 seat_r,请尝试以下代码。
seats =
seat_r:
index: vehicle.getBoneIndexByName('seat_r');
positions: Vector3Mp;
【讨论】:
【参考方案2】:您将seats
初始化为一个空对象。
let seats =
。
然后访问seats.seat_r
(与seats['seat_r']
相同),默认为undefined
。之后您尝试访问其不存在的index
属性(undefined.index
-> property 'index' of undefined
)。
为了解决这个问题,您必须将seats
的每个属性设置为VehicleSeatData
类型的空版本。
let seats: VehicleSeat =
'seat_r':
index: undefined,
positions: undefined,
,
'seat_pside_f':
index: undefined,
positions: undefined,
,
'seat_r':
index: undefined,
positions: undefined,
,
'seat_pside_f':
index: undefined,
positions: undefined,
,
;
// It is also enough to just initialize the properties as an empty object:
// let seats: VehicleSeat =
// 'seat_r': ,
// 'seat_pside_f': ,
// 'seat_r': ,
// 'seat_pside_f': ,
// ;
// Now you can access the properties and set its sub-properties.
seats['seat_r'].index = vehicle.getBoneIndexByName('seat_r');
seats['seat_pside_f'].index = vehicle.getBoneIndexByName('seat_pside_f');
seats['seat_r'].positions = vehicle.getWorldPositionOfBone(seats['seat_r'].index);
seats['seat_pside_f'].positions = vehicle.getWorldPositionOfBone(seats['seat_pside_f'].index);
这也意味着你可能需要改变你的类型
interface VehicleSeatData
index: number;
positions: Vector3Mp;
到
interface VehicleSeatData
index?: number;
positions?: Vector3Mp;
因为在此示例中,在您正确设置属性之前,这些属性可能是未定义的。
【讨论】:
有没有什么情况我不需要在使用之前先设置它们的属性?我希望我可以动态设置它们以上是关于未捕获的类型错误:无法设置未定义的属性“索引”的主要内容,如果未能解决你的问题,请参考以下文章