对不起,我之前给出的回答有误。在 TypeScript 中,对象字面量创建的类型为索引签名时,键必须是字符串或数字类型,并且无法直接重新赋值。
要实现重新赋值,您可以使用普通的对象(Plain Object)作为替代方案,或者使用Map数据结构来保存键值对。下面是两种可行的方法:
- 使用普通对象:
public playerNeedContainerIdTab = {
1: -1,
2: -1,
3: -1
};
// 对value进行重新赋值
this.playerNeedContainerIdTab[1] = newValue1;
this.playerNeedContainerIdTab[2] = newValue2;
this.playerNeedContainerIdTab[3] = newValue3;
- 使用
Map数据结构:
public playerNeedContainerIdTab = new Map<number, number>([
[1, -1],
[2, -1],
[3, -1]
]);
// 对value进行重新赋值
this.playerNeedContainerIdTab.set(1, newValue1);
this.playerNeedContainerIdTab.set(2, newValue2);
this.playerNeedContainerIdTab.set(3, newValue3);
希望这次能够帮到您。如果还有其他问题,请随时提问!
内容由零声教学AI助手提供,问题来源于学员提问




