Uncaught TypeError: Cannot read property ‘length’ of undefined / Cannot read property ‘0’ of undefined
问题描述
在写echarts的时候遇到找不到length
(已确认不是没有定义、或者名字输错的问题)然后我将this.cityList.length
替换成了数字,于是又出现了Cannot read property '0' of undefined
。
我的代码如下
mychart.on('click', function (params) {
console.log(params);
let selCity = params.name;
for(let i=0;i<this.cityList.length;i++){
if(selCity === this.cityList[i].name){
that.geoJson = this.cityList[i].cityJson;
}
}
console.log(selCity);
})
看着挺对的,但是实则陷入了一个误区,我一直将this理解为引用全局变量时使用的。
所以,接下来我将 this
输出了一下,发现了问题。this
指向ECharts
,自然获取不到我定义的全局变量cityList
。
问题解决
let that = this
最后代码修改如下,问题解决了
let that = this
mychart.on('click', function (params) {
console.log(params);
let selCity = params.name;
//console.log(this);
//console.log(that);
for(let i=0;i<that.cityList.length;i++){
if(selCity === that.cityList[i].name){
that.geoJson = that.cityList[i].cityJson;
console.log(that.geoJson);
}
else{
console.log("不符合");
}
}
console.log(selCity);
})
最后,一定要注意this的用法,千万不要陷入误区。
要是实在不清楚怎么用this,那咱就console输出一下,看看当前this指向什么。