You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于show变量筛选指定genre的books对象无结果问题修复

Fixing the Book Genre Filter Issue

Ah, I see the problem here! Your current filter logic isn’t working because you’re using map() inside the filter callback, which isn’t what filter() expects. Let me break this down and show you how to fix it.

The Problem with the Original Code

The filter() method expects its callback to return a boolean (true or false) to decide whether to keep an element. Right now, you’re returning the result of map(), which is an array. Even if none of the genres match, an array is always a truthy value—so your filter would end up including all books, not just the ones matching the genre. That’s why you’re not getting the expected result.

The Fix

Instead of map(), use the some() method. some() is perfect here because it checks if at least one element in the array meets your condition, and returns a boolean exactly what filter() needs.

Here’s the corrected code:

const booksToShow = show === "All" 
  ? books 
  : books.filter((book) => 
      book.genres.some(g => 
        g.toLocaleLowerCase() === show.toLocaleLowerCase()
      )
    );

Why This Works

  • some() iterates over each genre in the book’s genres array.
  • For each genre, it converts both the genre and the show value to lowercase (using toLocaleLowerCase() for proper case handling across locales) and checks if they match.
  • As soon as it finds a matching genre, it returns true, which tells filter() to keep that book. If no genres match, it returns false, and the book is excluded.

Testing this with show = "programming" will correctly return both JavaScript for Profissional and CSS for Profissional, since both have "Programming" in their genres.

内容的提问来源于stack exchange,提问作者Saddam Mohsen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 12:52:30