TypeError:Cannot read property ‘indexOf‘ of null问题解决方法

 

搜索功能:https://blog.csdn.net/bbs11007/article/details/110948483

 

根据这个搜索功能的写法,搜索的时候在本地调式木有问题,但是打包build为dist后,放到服务器后显示错误:Cannot read property ‘indexOf‘ of null

 let result = this.pages1.values.filter(row => {//this.pages1.values这个是表内所有数据
              //搜索那列的内容,这里搜索name、id等列的内容
              return row.name.indexOf(this.search1) > -1 
                || row.id.indexOf(this.search1) > -1 
                || row.code.indexOf(this.search1) > -1 
                || row.note.indexOf(this.search1) > -1;
            });

报错信息:

TypeError: Cannot read property 'indexOf' of null
    at app.43208ea5.js:1
    at Array.filter (<anonymous>)
    at o.sousuo (app.43208ea5.js:1)
    at click (app.43208ea5.js:1)
    at it (chunk-vendors.ffbff91e.js:34)
    at o.n (chunk-vendors.ffbff91e.js:34)
    at it (chunk-vendors.ffbff91e.js:34)
    at o.In.e.$emit (chunk-vendors.ffbff91e.js:34)
    at o.handleClick (chunk-vendors.ffbff91e.js:1)
    at it (chunk-vendors.ffbff91e.js:34)

也就是说这个indexOf使用时判断时前面的row.name这些报错,所有需要使用indexOf前对这些进行判断是否为空

 if(row.name!=null || row.id!=null || ....)这样太麻烦

我们可以写个方法:

contains(prop, str) { //打包到服务器:
            if (prop === null || prop === undefined) {
                return false;
            } else {
                return prop.indexOf(str) > -1;
            }
        },

然后修改写法,我下面时VUE的写法,调用contains是加this,如果是js就把this去掉

 let result = this.pages1.values.filter(row => {//this.pages1.values这个是表内所有数据
              //搜索那列的内容,这里搜索name、id等列的内容
               return this.contains(row.name, this.search1) 
                || this.contains(row.id, this.search1) 
                || this.contains(row.code, this.search1) 
                || this.contains(row.note, this.search1) 
            });

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章