javascript - 无法在 Typescript 中设置未定义的属性“你好”
问题描述
我正在尝试在 typescript 中创建一个类,但它总是会引发下面提到的错误。
下面是执行日志,它会引发错误。
[LOG]: "adding"
[LOG]: undefined
[ERR]: Cannot set property 'hello' of undefined
class CustomDataStructure {
private _data: any;
public CustomDataStructure() {
this._data = {};
}
public addItem(value: string) {
console.log("adding");
console.log(this._data)
this._data[value] = new Date().getTime();
}
public removeItem(key: string) {
delete this._data[key];
}
public showData() {
return this._data;
}
}
let ss = new CustomDataStructure();
ss.addItem("hello");
解决方案
您需要调用将this._data
值设置为空对象之类的构造函数:
class CustomDataStructure {
private _data: any;
constructor() {
this._data = {};
}
public addItem(value: string) {
console.log("adding");
console.log(this._data)
this._data[value] = new Date().getTime();
console.log(this._data)
}
public removeItem(key: string) {
delete this._data[key];
}
public showData() {
return this._data;
}
}
let ss = new CustomDataStructure();
ss.addItem("hello");
推荐阅读
- php - 在 Laravel/Cyber-duck excel 中获取 Excel 文件的特定单元格值
- c++ - Boost Log : 文件轮换
- arrays - 将两个公式合并为一个
- kubernetes - 自定义资源规范值返回 null
- amazon-web-services - 如何使用 Boto 3 获取每个 EC2 运行状况事件所属的实例 ID
- python - 为什么我的准确率趋于零,而我的损失却呈下降趋势?
- laravel - 在发送到端点之前在控制器中发出请求并过滤记录
- c++ - 是否允许重新定义类型名称?
- python - 有什么方法可以在 VScode 远程 ssh (windows) 中显示数字
- ios - Google Map 上的平滑移动标记在 Swift 3 中不起作用