js引起的 xxxx of null

在 vue 中操作 dom 元素的时候,报错 style of null

这个报错的原因,跟你代码的健壮性有关了;
这样就不会报错了


if( document.querySelectorAll(".now")[1] ){
    document.querySelectorAll(".now")[1].style.color="#606266"
    document.querySelectorAll(".now")[1].style.background="#fff"
}

你之前是这样写的


document.querySelectorAll(".now")[1].style.color="#606266"
document.querySelectorAll(".now")[1].style.background="#fff"

找不到对象(没有这个对象) 引起的 XXX of null

TypeError: Cannot read property 'length' of null at eval (personindex.vue?139c:438)

( res.data.notDone.applys.length > 8 ){
    报错
}

优化后

(res.data.notDone.applys&&res.data.notDone.applys.length>8){ 正确}

正确

if(str&&str.slice(0,4)=="http"){
   return str
}
 为啥要使用&&;因为没有时,就会报错,找不到对象
if(res.data&&res.data.length>5){
    this.newListArr = res.data ? res.data.slice(0,5) : []
}else{
    this.newListArr = res.data ? res.data: []
}

循环应该注意的事项

有可能 res.data 为 null

if(res.success==true && res.data ){
    for(let k=0;k<res.data.length;k++){ 这里可能报错
        if(res.data[k].frontCoverUrl){
            res.data[k]['showurl']='';
            console.log(111);

        }
    }
}
posted @   南风晚来晚相识  阅读(479)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示