解决vue+ts中报错:Cannot read property ‘push’ of undefined
一,出现的问题:
在vue项目中,用TypeScript定义了一个数组,遍历操作的时候,进行push操作时,查看控制台竟然出现“Cannot read property ‘push’ of undefined”错误, 代码如下:
public arr: Array<string>;
public created() {
for(let i = 0; i < this.routes.length; i++){
this.arr.push({name: this.routes[i].name})
}
console.log(this.arr,'---');
}
二,原因:
问题出现在typescript在转JavaScript的过程中,转换出来的JavaScript没有说明arr是一个数组,所以就运行报错了。
例如:

三,解决:
重新对arr进行初始化
public arr: Array<string> = []; //添加上一个中括号
public created() {
for(let i = 0; i < this.routes.length; i++){
this.arr.push({name: this.routes[i].name})
}
console.log(this.arr,'---');
}
在Vue.js项目中使用TypeScript时,遇到在遍历并尝试向数组push元素时报错'Cannot read property 'push' of undefined'。问题源于TS编译后的JS代码未明确声明数组类型。解决方案是对数组进行初始化,例如`public arr: Array<string> = [];`。在创建实例后,可以正常进行push操作,避免了运行时错误。

535

被折叠的 条评论
为什么被折叠?



