[英]How to tell if the list is empty using "filter" and "map"
list
.filter((val) => {
if (
val.name.toLocaleLowerCase().includes(input))
) {
return val
}
})
.map((val, idx) => (
<Li
key={idx}
/>
))
Using this structure, I wanted to do something if returns empty.使用这个结构,我想在返回空时做一些事情。
Ex: When searching for "abc" and there is no "abc" in the list, a message appears saying that "abc" was not found.例如:当搜索“abc”并且列表中没有“abc”时,会出现一条消息说找不到“abc”。
Several things to change:要改变的几件事:
list
.filter((val) => {
if (
val.name.toLocaleLowerCase().includes(input))
) {
return val
}
})
can be just可以只是
list
.filter(val => val.name.toLocaleLowerCase().includes(input)
Remember that the function inside filter
just returns a true
or false
.请记住,
filter
内的函数只返回true
或false
。 By chance your expression, which returns the actual list element, is interpreted as true
, and when your expression does not match, you don't return anything, which has the same effect as returning false
.偶然地,您返回实际列表元素的表达式被解释为
true
,并且当您的表达式不匹配时,您不返回任何内容,这与返回false
具有相同的效果。 Expressing it as above makes it clearer what you are doing (and is very marginally faster).如上表达它可以更清楚地了解你在做什么(并且速度非常快)。
const matches = list.filter(val => val.name.toLocaleLowerCase().includes(input)
const output = (matches.length>0) ?
matches.map((val, idx) => (
<Li
key={idx}
/>
)) : (
<div>Not found</div>
)
You can tell if the list is empty using "filter" and "map" by using following JavaScript Code:您可以使用以下 JavaScript 代码使用“过滤器”和“映射”判断列表是否为空:
list
.filter((value) => (value!==undefined) && (value!==null) && value.name.toLocaleLowerCase().includes(input)))
.map((value, id) => (
<Li
key={id}
/>
))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.