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>
3

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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.');
    }

Comments

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>

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.