【问题标题】:How do I handle indexOf returning 'null' without using try/catch(err)?如何在不使用 try/catch(err) 的情况下处理返回“null”的 indexOf?
【发布时间】:2017-07-14 23:50:12
【问题描述】:

我正在用数据填充表格 - 使用 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% 按预期工作并处理返回 null 的 indexOf...但这不是正确处理它的方法 - 我假设这种异常处理是,嗯,应该用于罕见的例外情况,并且不应该像后端一样在前端使用。

如何处理上述 Javascript 代码中返回 null 的 indexOf?它可能在正在填充的任何源列中返回 null。

【问题讨论】:

  • indexOf 应该返回 8 个 -1 或任何索引,从不为空。如果它抛出错误,那不是因为它返回null。您可以使用示例数据在 sn-p 中完成这项工作吗?
  • indexOf 在数组上运行时永远不会返回null;您前面的变量之一(backendInfo 或其属性之一)必须是罪魁祸首。您得到的确切错误文本是什么?
  • 对不起。我的措辞很糟糕。输入数据可能有一个值为空的键。我正是这个意思。我得到的错误是Uncaught TypeError: Cannot read property 'indexOf' of null
  • 那么错误类似于Cannot read property 'indexOf' of undefined" 吗?这会有所作为
  • @Randy 我只是把错误放在上面-Uncaught TypeError: Cannot read property 'indexOf' of null

标签: javascript arrays reactjs fixed-data-table


【解决方案1】:

如果找不到key,JS会抛出错误。 Try-catch 是修复这些错误的好方法,但还有另一种选择:

您可以在将值推入对象之前检查对象中是否存在键。

var data = { };

var key = "test";

// your method works great
try {
  var value = data.firstname.indexOf(key);
} catch (err) {}

// another method, I'd prefer the try/catch
var value = data.firstname ? data.firstname.indexOf(key) : undefined;


// test if the object is the type of object you are looking for
// this is in my opinion the best option.
if(data.firstname instanceof Array){
  var value = data.firstname.indexOf(key);
}


// you can use the last option in your code like this:

var firstnameHasKey = data.firstname instanceof Array && ~data.firstname.indexOf(key);
var lastnameHasKey = data.lastname instanceof Array && ~data.lastname.indexOf(key);
if(firstnameHasKey || lastnameHasKey){
  // logics
}

如果你测试instanceof && indexOf,永远不会出错。如果firstnameundefined,则永远不会检查indexOf

当然,您可以将其用于其他类型:

var myDate = new Date();
myDate instanceof Date;     // returns true
myDate instanceof Object;   // returns true
myDate instanceof String;   // returns false

MDN documentation

【讨论】:

  • 我尝试在一个 if 语句中实现整个事情;它不会抛出错误,但搜索功能很差。我会尝试按照您的建议创建变量。
  • @cbll 您唯一需要更改的是检查instanceof 是否设置正确。那不应该改变结果,只是防止错误。我偶然有firstnameHasKey &amp;&amp; lastnameHasKey,那显然应该是firstnameHasKey || lasthameHasKey
  • 但是我们仍然应该检查 indexOf 是否不返回 -1 吗?
  • 我试过了,但搜索仍然没有像 try/except 一样工作:/
  • 尝试制作一个运行的jsfiddle或sn-p,我会看看我能为你做些什么。
猜你喜欢
  • 2012-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
  • 1970-01-01
  • 2016-05-06
相关资源
最近更新 更多