TypeError: Cannot read property 'xxxx' of undefined的解决方法

在vue或者js中,使用.length的时候在浏览器的控制台中经常会报TypeError: Cannot read property 'length' of undefined的错误,类似的错误还有很多,大多都是TypeError: Cannot read property 'xxx' of undefined,出现这种错误的原因很简单,就是你调用该方法或函数的字符串或数组、对象等等出现了为空的情况,加一个判断就好了。

例子:
下面的代码会报TypeError: Cannot read property 'length' of undefined的错误

let txtDom = this.$refs.textContainer;
for (let i = 0; i < txtDom.length; i++) {
       let curHeight = txtDom[i].offsetHeight;
       if (curHeight > twoHeight) {
           this.$set(this.als, i, Object.assign({}, this.als[i], { status: true }))
       } else {
           this.$set(this.als, i, Object.assign({}, this.als[i], { status: true }))
       }
}

原因就是txtDom出现了为空的情况,所以就没有length的属性了。解决方法就是判断txtDom是否为空,如下:

let txtDom = this.$refs.textContainer;
if(txtDom){
     for (let i = 0; i < txtDom.length; i++) {
         let curHeight = txtDom[i].offsetHeight;
         if (curHeight > twoHeight) {
             this.$set(this.als, i, Object.assign({}, this.als[i], { status: true }))
         } else {
             this.$set(this.als, i, Object.assign({}, this.als[i], { status: true }))
         }
     }
 }

上面是在js中的代码报错,有时候我们在html中也会使用一些函数或方法,也要做判断,如下al.time是从后端读取的数据,可能会为空,会报TypeError: Cannot read property 'substring()' of undefined的错误:

<el-tag size="mini"   v-if="al.time">发布时间</el-tag>{{ al.time.substring(0,10)}}

解决方法是使用三元运算符做判断:

<el-tag size="mini"   v-if="al.time">发布时间</el-tag>{{ al.time ? al.time.substring(0,10):al.time}}

这样就可以完美解决问题了。

  • 21
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值