我正在用數據填充表 - 使用fixed-data-table
,這是一個React.js組件。但是,在現階段這並不重要。如何在不使用try/catch(err)的情況下處理indexOf返回'null'?
表中有問題源於的搜索框。
首先,這裏是代碼的有趣部分。
for (var index = 0; index < size; index++) {
if (!filterBy || filterBy == undefined) {
filteredIndexes.push(index);
}
else {
var backendInfo = this._dataList[index];
var userListMap = hostInfo.userList;
var userListArr = Object.values(userListMap);
function checkUsers(){
for (var key in userListArr) {
if (userListArr.hasOwnProperty(key) && userListArr[key].text.toLowerCase().indexOf(filterBy) !== -1) {
return true;
}
}
return false;
}
if (backendInfo.firstName.indexOf(filterBy) !== -1 || backendInfo.lastName.toLowerCase().indexOf(filterBy) !== -1 || backendInfo.countryOrigin.toLowerCase().indexOf(filterBy) !== -1
|| backendInfo.userListMap.indexOf(filterBy) !== -1) {
filteredIndexes.push(index);
}
}
}
這是渲染和最後一部分是拋出錯誤,如果你輸入的東西在桌上,一列返回用戶輸入null
。
的事情是,我可以使代碼工作,如果我改變的最後部分..
try {
if (backendInfo.firstName.indexOf(filterBy) !== -1 || backendInfo.lastName.toLowerCase().indexOf(filterBy) !== -1 || backendInfo.countryOrigin.toLowerCase().indexOf(filterBy) !== -1
|| backendInfo.userListMap.indexOf(filterBy) !== -1) {
filteredIndexes.push(index);
}
}
catch(err) {
console.log('Exception')
}
隨着try/catch語句,它的工作原理100%按預期和處理的indexOf返回null .. 。但這不能成爲正確處理它的方式 - 我假設這種異常處理應該是罕見的例外,並且不應該在前端使用真正的異常處理後端。
如何在上面的Javascript代碼中處理indexOf返回null?它可能會在任何正在填充的源列中返回null。
的indexOf應該返回eighter'-1'或任何索引,永遠不爲null。如果它拋出一個錯誤,那不是因爲它返回null。您可以使用樣本數據在片段中完成此項工作嗎? – Randy
'indexOf'在數組上運行時永遠不會返回'null';你的一個前面的變量('backendInfo'或它的一個屬性)必須是罪魁禍首。什麼是你得到確切的錯誤文字? – gyre
對不起。我的自言自語很差。輸入數據可能有一個鍵值爲null的鍵。我正是這個意思。我得到的錯誤是'未捕獲的TypeError:無法讀取屬性'indexOf'的空' – cbll