JS中如何用If else实现多输入值对应同一输出?
Hey there! Great question—you’re right that your current code only handles the "history" case, and we can fix this in a couple of clean, maintainable ways. Let’s break it down:
Option 1: Combine Conditions with Logical OR (||)
If you only have a small number of trigger values, you can bundle them into a single if statement using the logical OR operator. This keeps things simple for short lists:
<script type="text/javascript"> var book = "mata"; // Replace with your input value // Check if the book matches any math-related keyword if (book === "maths" || book === "mathematics" || book === "mata" || book === "maths book") { document.write("<b>Maths Book</b>"); } else if (book === "history") { document.write("<b>History Book</b>"); } else { // Optional: Handle unexpected values document.write("<b>Unknown Book</b>"); } </script>
Pro tip: I used === (strict equality) instead of == here—it’s a JavaScript best practice to avoid weird type coercion bugs.
Option 2: Use an Array with includes() (Better for Scaling)
If you might add more trigger values later, storing them in an array and using the includes() method is way easier to maintain. No need to chain endless || operators—just update the array:
<script type="text/javascript"> var book = "mathematics"; // Example input // Store all math-related triggers in one array const mathBookTriggers = ["maths", "mathematics", "mata", "maths book"]; if (mathBookTriggers.includes(book)) { document.write("<b>Maths Book</b>"); } else if (book === "history") { document.write("<b>History Book</b>"); } else { document.write("<b>Unknown Book</b>"); } </script>
This approach scales beautifully—if you want to add "math" or "math textbook" later, just drop it into the array and you’re done.
Quick Note on Your Original Code
Your initial script only checked for the "history" value and had no logic for math-related inputs. By flipping the order (checking math triggers first) and adding the right conditions, we get the behavior you’re looking for.
内容的提问来源于stack exchange,提问作者dentist

