【发布时间】:2021-04-05 03:51:47
【问题描述】:
所以我试图在我的应用程序中使用 windows.localstorage 创建一个对象数组。
export class MyListComponent implements OnInit {
public myStorage = window.localStorage;
public list : any [] = [];
public empty = true;
constructor() { }
ngOnInit(): void {
for(var k in window.localStorage) {
var temp = this.myStorage[k].split(",");
console.log(temp);
if(temp.length == 4) {
let item = {
id: k,
type: temp[1]
}
this.empty = false;
this.list.push(item);
console.log(item);
}
}
console.log(this.list);
}
}
由于某种原因,最后一行 console.log(this.list) 似乎没有工作,或者换句话说,没有添加任何内容。我不确定为什么会这样,因为所有其他控制台日志似乎都在工作,例如 console.log(temp) 和 console.log(item)。我的控制台还显示以下错误:
ERROR TypeError: this.myStorage[k].split is not a function at MyListComponent.ngOnInit
这是为什么呢?如果没有成功拆分,则不会创建 temp。如何将我的项目对象添加到我的列表数组中,为什么 this.myStorage.split 会出现类型错误?
【问题讨论】:
标签: javascript arrays angular typescript