求助:如何用JavaScript获取用户输入并判断值是否存在于数组中
How to Check if User Input Exists in a JavaScript Array
Hey there! Let's fix your code and get this working properly. First, let's break down the issues with your current implementation:
What's Wrong With Your Current Code?
- Incorrect Check Logic: Your
checkfunction usesif(a===list[a]), which tries to compare the input value to the array element at indexa—this isn't how you check if a value exists in an array. For example, if you input 20, it would try to compare 20 tolist[20](which is undefined, since your array only has 10 elements). - Type Mismatch: The
prompt()function returns a string, but your array contains numbers. Comparing a string to a number directly (like"20" === 20) will always return false.
Fixed Solution Using a For Loop
Since you mentioned wanting to use a for loop, here's how to implement that correctly:
function check(inputValue, numberList) { // Convert user input from string to number to fix type mismatch const num = Number(inputValue); let isPresent = false; // Loop through every element in the array for (let i = 0; i < numberList.length; i++) { if (numberList[i] === num) { isPresent = true; break; // Exit loop early once we find a match to save resources } } // Display the result if (isPresent) { document.write("Number is Present"); } else { document.write("Number is not Present"); } } const list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]; const n = prompt("Enter any Number"); check(n, list);
Key Improvements:
- We convert the user input to a number with
Number(inputValue)to resolve the type mismatch issue. - The for loop iterates over each element in the array, checking for a match with the converted input number.
- A boolean flag
isPresenttracks whether we found a match, and we break out of the loop early once a match is found.
Simpler Alternative: Using Array.includes()
If you don't strictly need a for loop, JavaScript has a built-in method includes() that simplifies this check drastically:
const list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]; const n = prompt("Enter any Number"); const num = Number(n); if (list.includes(num)) { document.write("Number is Present"); } else { document.write("Number is not Present"); }
This method handles the iteration internally and returns true if the value exists in the array, false otherwise—super clean and concise!
内容的提问来源于stack exchange,提问作者Aashir Irshad
相关产品推荐
相关产品推荐

