使用IndexOf()过滤返回空白结果

时间:2017-04-21 12:55:33

标签: javascript indexof

我在列表中运行了一个过滤器,看起来像这样。

if (!(this.state.filter && c.lastName && c.lastName.toLowerCase().indexOf(this.state.filter) == -1)) {
                return true
} else if (!(this.state.filter && c.firstName && c.firstName.toLowerCase().indexOf(this.state.filter) == -1)){
                return true
} else if (!(this.state.filter && name && name.toLowerCase().indexOf(this.state.filter) == -1)){
                return true
}  else if (!(this.state.filter && c.email && c.email.toLowerCase().indexOf(this.state.filter) == -1)){
                return true
} else {
                return false
}

但是,由于null0''都匹配该查询,因此每个过滤器都会返回没有名字,姓氏或电子邮件的所有人。< / p>

我知道我可以通过为每个项目分别设置过滤字段来区分它,但似乎必须有更好的方法来匹配空字符串?

2 个答案:

答案 0 :(得分:2)

您需要检查您的属性是否为字符串类型,而不是

... && c.lastName && ...

它需要:

... && typeof c.lastName === 'string' && ...

为了浓缩一下,你可以这样做:

return !this.state.filter
        || [c.lastName, c.firstName, name, c.email].some( 
                value => typeof value === 'string' 
                        && value.toLowerCase().includes(this.state.filter) );

&#13;
&#13;
var test = {
    state: {},
    test: function(c, name) {
        return !this.state.filter
            || [c.lastName, c.firstName, name, c.email].some( 
                    value => typeof value === 'string' 
                            && value.toLowerCase().includes(this.state.filter) );
    }
}

test.state.filter = 'abcd';
var res = test.test({ lastName: 'Mr abc', firstName: 'Helen' }, '');
console.log(res);
res = test.test({ lastName: 'Mr abcd', firstName: 'Helen' }, 'John');
console.log(res);
res = test.test({ lastName: 0, firstName: null }, NaN);
console.log(res);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果目标是返回true c.lastNamec.firstNamename(它是否正确,c.?),或c.email包含this.state.filter,您只需执行以下操作:

if (this.state.filter &&
    (c.lastName.toLowerCase().indexOf(this.state.filter) != -1 ||
     c.firstName.toLowerCase().indexOf(this.state.filter) != -1 ||
     name.toLowerCase().indexOf(this.state.filter) != -1 ||
     c.email.toLowerCase().indexOf(this.state.filter) != -1
   )) {
    // There's a filter and at least one thing matched
    return true;
} else {
    // There's no filter, or it didn't match anything
    return false;
}

如果你真的要归还,那么就不需要if

return (this.state.filter && (
    c.lastName.toLowerCase().indexOf(this.state.filter) != -1 ||
    c.firstName.toLowerCase().indexOf(this.state.filter) != -1 ||
    name.toLowerCase().indexOf(this.state.filter) != -1 ||
    c.email.toLowerCase().indexOf(this.state.filter) != -1
));

除非它们可能不是字符串,否则无需测试c.lastName等真实性。

或者,通过字符串连接,我们只需要toLowerCase().indexOf()一次:

return (this.state.filter &&
    (c.lastName + "\t" + c.firstName + "\t" + name + "\t" + c.email).toLowerCase()
        .indexOf(this.state.filter) != -1
);

...假设this.state.filter不能包含标签。