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

求助:如何用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 check function uses if(a===list[a]), which tries to compare the input value to the array element at index a—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 to list[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 isPresent tracks 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:57:35