[英]Eloquent Javascript: Uncaught TypeError: Cannot read property 'indexOf' of undefined
[英]Javascript: Uncaught TypeError: Cannot read property 'indexOf' of null
我正在使用數據填充表-使用fixed-data-table
,它是一個React.js組件。 但是,在當前階段這還不那么重要。
表格上有一個搜索框,此問題出自此。
首先,這是代碼中有趣的部分。
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……但這不是正確處理它的方法-我假設這種異常處理應該是對於極少數的例外,不應在前端使用太多,在后端也不應使用。
如何在不使用try / catch的情況下處理標題中的錯誤?
您正在使用indexOf
,因此請確保這些值不會是undefined or null
,您可以通過對每個值進行檢查來解決此問題,如下所示:
let {firstName, lastName, countryOrigin, userListMap} = backendInfo;
if ((firstName && firstName.indexOf(filterBy) !== -1)
|| (lastName && lastName.toLowerCase().indexOf(filterBy) !== -1)
|| (countryOrigin && countryOrigin.toLowerCase().indexOf(filterBy) !== -1)
|| (userListMap && userListMap.indexOf(filterBy) !== -1)) {
filteredIndexes.push(index);
}
解決此問題的其他方法是,您為這些變量firstName, lastName, countryOrigin, userListMap
定義的默認值,如果它們是數組,則應為[]
,如果為string,則應為''
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.