【问题标题】:Why does returning arr.includes() is different than returning true in a conditionnal statement verifying the same array?为什么返回 array.includes() 与在验证同一数组的条件语句中返回 true 不同?
【发布时间】:2020-10-31 23:25:45
【问题描述】:

我正在构建一个“搜索引擎”,以便我的客户可以根据其类别和 ID 访问一些文档。为此,我过滤了所有可用的文档,因此我只显示与当前页面匹配的那些(它可以是新闻页面、财务页面、事件页面等)

我遇到了一个错误,幸运的是,我发现有一个我仍然不明白的区别......

案例 1 给我 113 个结果

const allDocuments = [{id: 1, ....}, {id: 2, ....}, {id: 3, ...}, ...]
const currentPageIds = [1, 2, 3]

const filteredDocuments = allDocuments.filter(document => {
          // each document have one or more category ids
          for(const categoryID of document.category_id) {
            return currentPageIds.includes(categoryID)
        }
      })

案例 2 给我 134 个结果

const allDocuments = [{id: 1, ....}, {id: 2, ....}, {id: 3, ...}, ...]
const currentPageIds = [1, 2, 3]

const filteredDocuments = allDocuments.filter(document => {
          // each document have one or more category ids
          for(const categoryID of document.category_id) {
            if(currentPageIds.includes(categoryID)) {
              return true
            }
         }
      })

据我了解,函数 includes() 应该返回一个布尔值,所以在我的示例中,它与在条件语句中返回 true 有何不同?

感谢您的帮助!

【问题讨论】:

  • 请添加一些带有category_id的数据。
  • 你的第一个sn-p从for(const categoryID of document.category_id) {的第一次迭代立即returns,只检查第一个类别是否包含在currentPageIds中,而忽略其他类别。
  • @NinaScholz 数据在这里无关紧要,因为我的问题是关于直接返回函数 include() 或使用条件语句然后返回 true 的预期行为
  • 第一个 on 只循环一次。对于每个document
  • @Bergi 哦,我的上帝……我犯了这么一个菜鸟错误。我不知道我怎么错过了这个!谢谢

标签: javascript return include conditional-statements


【解决方案1】:

如果我们将您的案例 1 转换为您的案例 2 的方向。它将是以下代码。在您的案例 2 中,缺少 else 块。这可能是导致结果不同的原因。

for (const categoryID of document.category_id) {
  if (currentPageIds.includes(categoryID)) {
    return true;
  } else {
    return false;
  }
}

或者,您可以尝试

const filteredDocuments = allDocuments.filter((doc) =>
  doc?.category_id?.some((id) => currentPageIds.includes(id))
);

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    问题出在案例 1 的逻辑中,对于应该返回 true 的案例,您在该处返回 false,这解释了案例 1 找到较少案例的原因

    更多解释见下一段代码中的cmets

    const filteredDocuments = allDocuments.filter(document => {
              // each document have one or more category ids
              for(const categoryID of document.category_id) {
                // here sometimes you are returning false, when you should be returning true
                // this happens here for example when the first category 
     // in document.category_id is not included in currentPageIds, while next pages in document.category_id may be included
                return currentPageIds.includes(categoryID)
            }
          })
    

    【讨论】:

      猜你喜欢
      • 2013-12-17
      • 2020-11-24
      • 1970-01-01
      • 2019-05-07
      • 2015-05-06
      • 2018-08-06
      • 2013-11-10
      • 2020-04-02
      • 2021-05-06
      相关资源
      最近更新 更多