如何实现用户输入与预设数据的匹配验证?问题代码求助优化
Ah, I see the issue here! Let's fix that annoying repeated error message problem for you.
What's Wrong With the Current Code
Your code uses forEach to loop through every user in the data array. That means every time a user doesn't match the input ID, it prints "Incorrect ID"—even if there's a matching user later in the list. For example, if you enter ID 1, you'll get one "Welcome" log followed by two "Incorrect ID" logs from the other users. We need to check if the ID exists once after checking all users, not on every iteration.
Fixed Implementation (Using Array.find())
This is the cleanest approach—we'll find the matching user first, then decide what to output based on whether we found a match. Also, note that user input is a string, so we need to convert it to a number to match the numeric userId values:
const userInput = document.querySelector(".ID"); const button = document.querySelector(".login"); const data = [ { userName: "Jon", userId: 1, admin: true }, { userName: "Mike", userId: 2, admin: false }, { userName: "Martha", userId: 3, admin: false }, ]; function checkUser() { // Convert input string to number to match userId type const inputId = Number(userInput.value); // Find the first user with a matching userId const matchedUser = data.find(user => user.userId === inputId); if (matchedUser) { console.log(`Welcome ${matchedUser.userName}!`); } else { console.log("Incorrect ID"); } } button.addEventListener("click", (e) => { e.preventDefault(); checkUser(); });
Alternative Options
If you only need to check existence (not get the user data), you can use Array.some():
function checkUser() { const inputId = Number(userInput.value); const idExists = data.some(user => user.userId === inputId); idExists ? console.log("Welcome") : console.log("Incorrect ID"); }
Or a manual loop with a break (great for understanding the flow):
function checkUser() { const inputId = Number(userInput.value); let isIdFound = false; for (const user of data) { if (user.userId === inputId) { isIdFound = true; break; // Stop looping once we find a match } } console.log(isIdFound ? "Welcome" : "Incorrect ID"); }
Key Takeaways
- Don't output results inside a loop that checks every item—wait until you've confirmed if a match exists.
- Always watch out for type mismatches (string input vs. numeric
userIdin your case).
内容的提问来源于stack exchange,提问作者user14831698

