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

 

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