gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:46:28 25 4
gpt4 key购买 nike

我正在一个如下所示的列表上运行过滤器。

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'' 都与该查询匹配,因此每个过滤器都会返回所有没有名字、姓氏或电子邮件。

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

最佳答案

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

... && 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) );

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

关于javascript - 使用 IndexOf() 过滤返回空白结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43543291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com