0

I am wanting to create a very simple script that checks user's input to a pre-existing array. However, it doesn't seem to work and I'm not sure why. Please, keep in mind I'm new to this and trying to learn.

<script>
    var usernumber = prompt('What is your number?');
    var numbers = ['1', '2', '3'];
    if (usernumber == 'numbers') //If the user number matches one of preset numbers
    {
        alert('Match');
    } else {
        alert('No match found.');
    }
</script>
rebirthrelive
  • 11
  • 1
  • 2
  • Possible duplicate of [**How do I check if an array includes an object in JavaScript?**](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript) – cнŝdk Nov 13 '17 at 14:37
  • You should explain what exactly it's doing incorrectly, versus what you want. – user3556757 Nov 13 '17 at 14:38
  • You're going to find that there are many ways to skin this cat. If you visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array You can learn about how to manipulate your array and choose the best solution for what you're attempting to do. – Chris Nov 13 '17 at 14:42

5 Answers5

4

You can use Array.indexOf prototype function here:

if(numbers.indexOf(usernumber) >= 0){
    alert('Match');
}

Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

Taha Paksu
  • 15,371
  • 2
  • 44
  • 78
1

this will work fine for you

<script>
    var usernumber = prompt('What is your number?');
    var numbers = ['1', '2', '3'];
    for(i=0;i<=numbers.length;i++)    
     {if (usernumber == numbers[i]) 

    {
        alert('Match');
         break;
    } }
     if(i==numbers.length) {
        alert('No match found.');
    }
</script>
Hemant Rajpoot
  • 683
  • 1
  • 11
  • 29
1

You can check the following code

    var usernumber = prompt('What is your number?');
    var numbers = ['1', '2', '3'];
    if (numbers.indexOf(usernumber) >=0 ) //If the user number matches one of preset numbers
    {
        alert('Match');
    } else {
        alert('No match found.');
    }
UchihaItachi
  • 2,602
  • 14
  • 21
1

array.indexof(item) return -1 if the item does not exist on the array else return item's index

<script>
    var usernumber = prompt('What is your number?');
    var numbers = ['1', '2', '3'];
    if (numbers.indexOf(usernumber) >=0 ) // check if the item exists on the array
    {
        alert('Match');
    } else {
        alert('No match found.');
    }
</script>
0
 <script>
    var usernumber = prompt('What is your number?');
    var numbers = new Array();
    numbers['1'] = true;
    numbers['2'] = true;
    numbers['3'] = true;
    if (numbers[usernumber]) //If the user number matches one of preset numbers
    {
        alert('Match');
    } else {
        alert('No match found.');
    }
</script>
Erick Lanford Xenes
  • 1,467
  • 2
  • 20
  • 34