如何包括数组的整个长度? [英] How to include the entire length of arrays?

查看:39
本文介绍了如何包括数组的整个长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面,我创建了此过滤器方法,以仅显示在fullDetails数组中找到的内容.

Below I created this filter method to only display what's found within the fullDetails array.

如果这个问题不清楚,或者使用的术语错误,我深表歉意.

I apologize if this question is unclear and if I'm using the wrong terminology.

现在,如果我输入每个单独的元素(例如,fullDetails [0]),它将可以正常工作.但是数组有4个元素.我如何编写它使其包括数组的整个长度?(即[0] [1] [2] [3])?

Right now it can work if I input each element individual (eg. fullDetails[0]). But the array has 4 elements. How can I write it so that it includes the entire length of array? (ie. [0] [1] [2] [3])?

let modItemList = this.props.items.filter(
        (item) => {
            return item.fullDetails[0].toLowerCase().indexOf(this.state.searchItems.toLowerCase()) !== -1;
        }
    );

推荐答案

如果您的过滤器应保留 fullDetails 数组包含 this.state.searchItems 的项目(大小写-不敏感),您正在寻找 some 数组方法:

If your filter is supposed to keep items whose fullDetails array contains this.state.searchItems (case-insensitive), you're looking for the some method of arrays:

let lc = this.state.searchItems.toLowerCase(); // Do this once
let modItemList = this.props.items.filter(
    (item) => item.fullDetails.some(e => e.toLowerCase().indexOf(lc) !== -1)
);

some 为数组中的每个条目调用其回调,如果回调返回真值,则停止并返回 true (如果从未返回,则 some 返回 false ).

some calls its callback for each entry in the array, stopping and returning true if the callback returns a truthy value (if it never does, some returns false).

代替 indexOf ,您还可以使用

Instead of indexOf, you could also use includes (ES2015, like let and arrow functions):

let lc = this.state.searchItems.toLowerCase(); // Do this once
let modItemList = this.props.items.filter(
    (item) => item.fullDetails.some(e => e.toLowerCase().includes(lc))
);

这篇关于如何包括数组的整个长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆