【问题标题】:JS Filter returning empty arrayJS 过滤器返回空数组
【发布时间】:2023-01-25 14:11:34
【问题描述】:

我正在尝试过滤 reactJS 中的列表以仅包含其中包含文本“JR:”的元素,但是由于某种原因过滤器返回一个空数组。我是 JS 的新手,来自 Java 背景,所以可能认为问题可能是我在 forEach 中返回,而不是过滤器?不确定,任何帮助将不胜感激。

谢谢

        let updated = this.widgetCopy
        const filtered =  updated.filter((widget)=>{
             this.state.selected.forEach((status)=>{
                if(status.includes("JR:")){
                    console.log(widget)
                    return widget.jr !== null
                }else{return true}
            })
        })
        console.log(filtered)

【问题讨论】:

  • 请将您的输入/输出数据样本作为 minimal reproducible example 添加到问题中。但主要原因是您无法从forEach 返回,因此您可能还必须在所选状态上使用额外的filter。取决于那是什么。
  • 缺少信息,什么是“更新的”,确切地包含字符串数组,字符串数组或对象数组?如果它是字符串数组,则不应使用过滤器。你不需要 foreach

标签: javascript reactjs ecmascript-6


【解决方案1】:

.forEach 需要一个函数作为第一个参数。如果你试图在那个函数中返回任何东西,它什么也不会做; .forEach 将继续遍历其余元素,并将评估为 undefined。

由于您不希望这样,请使用 for .. of 循环。

但是,您的代码逻辑没有意义。

您尝试使用原始代码执行的操作看起来是:

  • 过滤更新,保留如果:

    • 状态包括“JR:”,在这种情况下返回widget.jr !== null
    • 如果在没有任何“JR:”之前出现一个状态,返回true
let updated = this.widgetCopy;
const filtered = updated.filter((widget) => {
  for (const status of this.state.selected) {
    if (status.includes("JR:")) {
      console.log(widget);
      return widget.jr !== null;
    } else {
      return true;
    }
  });
});
console.log(filtered);

【讨论】:

    猜你喜欢
    • 2022-10-14
    • 2021-07-13
    • 2017-07-02
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    相关资源
    最近更新 更多