JS输入搜索优化:输入框为空时不返回任何结果
I get it—you’re running into this annoying issue where deleting all text from your search input brings up every character in your array instead of showing nothing. Let’s fix that quickly!
The Root Cause
The problem happens because when your query is an empty string (""), the includes("") check returns true for any string. So your filter ends up keeping every item in the array instead of filtering them out.
The Solution
We just need to add a quick check at the start of your search function: if the trimmed query is empty, return an empty array immediately. Here’s how to adjust your code with your characters array:
const characters = [ { first_name: "Abraham", last_name: "Lincoln", img: "https://upload.wikimedia.org/wikipedia/commons/a/ab/Abraham_Lincoln_O-77_matte_collodion_print.jpg" }, { first_name: "Johnny", last_name: "Bravo", img: "https://ia.media-imdb.com/images/M/MV5BYTg4MDkwODgtYTBlNy00Yjc2LTg4NTYtZGE5YmFhYjY5NzU2XkEyXk..." } ]; function searchCharacters(query) { // Trim whitespace first to handle cases where user enters spaces then deletes them const trimmedQuery = query.trim(); // If the query is empty after trimming, return nothing if (!trimmedQuery) { return []; } // Normal search logic for non-empty queries const lowerCaseQuery = trimmedQuery.toLowerCase(); return characters.filter(character => character.first_name.toLowerCase().includes(lowerCaseQuery) || character.last_name.toLowerCase().includes(lowerCaseQuery) ); }
Key Details
- Using
trim()ensures we ignore accidental spaces (like if the user taps spacebar then deletes it—we still treat that as an empty query). - We convert the query to lowercase once (instead of inside the filter) for a tiny performance boost, but that’s optional.
- Empty query? Boom—return an empty array right away, no need to run the filter at all.
Example Usage with an Input
If you’re using this with an HTML input, here’s how you’d hook it up:
const searchInput = document.getElementById('searchInput'); searchInput.addEventListener('input', (e) => { const results = searchCharacters(e.target.value); // Update your UI with results here—empty array means no items to show! console.log(results); // Will log [] when input is empty });
Now when you clear the input, you’ll get zero results instead of the full list of characters. Perfect!
内容的提问来源于stack exchange,提问作者user4889134

