Uncaught TypeError: Cannot read property ‘length‘ of undefined( /property ‘0‘ of undefined)

4 篇文章 0 订阅

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指向什么。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值