3

I'm having an array:

var something = ["1","2","3","4"] ;

I'll ask the user in a prompt to pick a number. if it corresponds to any value in the array it triggers something.

My question is: How do i check if the input corresponds to any array value?

if(something === "input"){
    console.log("u picked a good number");
} 

Of course if statement i have now is incorrect, but how do i make it check every value in the array, and see if anything corresponds?

Would be awsome if someone could help me on this one! ;)

thxx!

2

1 Answer 1

9

Arrays have an indexOf method which returns the index at which the argument was found in the array, or -1 if it wasn't found:

if (something.indexOf(input) > -1) {
    // In the array!
}

Note that some older browsers don't support this method, but there is a polyfill in the MDN article linked to above.

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

1 Comment

Thx! this helped me alot. it works :) you made me a bit wiser!

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.