解决vue+ts中报错:Cannot read property ‘push’ of undefined
一、问题
在vue项目中,用TypeScript定义了一个数组,遍历操作的时候,进行push操作时,查看控制台竟然出现“Cannot read property ‘push’ of undefined”错误, 代码如下:
const arr: Array<string>
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是一个数组,所以就运行报错了。
例如:
三、解决
const arr: Array<string> = [] // 这!!!!!!!!
for(let i = 0; i < this.routes.length; i++){
this.arr.push({name: this.routes[i].name})
}
console.log(this.arr,'---');