2

I have two vars like so:

var numberArray = [0,10,20,30,40,50];
var chosenNumber = 20;

How do I compare chosenNumber to numberArray to access its key in the array ([2])?

2 Answers 2

7

I think you might want to use indexOf:

var index = numberArray.indexOf(chosenNumber);
Sign up to request clarification or add additional context in comments.

1 Comment

so simple. so clean +1. ( my mind went to very far directions - and not this simple one...)
1

I'm not so sure what you're trying to achieve, but it sounds like you want to grab the index?

If so, use .indexOf() like

numberArray.indexOf( chosenNumber ); // 2

If you pass in a value to .indexOf() which can not get found in the array, it returns -1 instead. Since Arrays in ECMAscript are just "special" Objects, each key behind a value is just the numerical index.

numberArray = {
    0: 0,
    1: 10,
    2: 20,
    3: 30 // and so forth
};

If we would create a new Object that inherits from Array.prototype and also give it a length property, tada, we would have just created a Javascript Array.

1 Comment

For not found returns -1, not undefined.

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.