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);

        }
    }
}
原文地址:https://www.cnblogs.com/IwishIcould/p/13302227.html