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])?
I think you might want to use indexOf:
var index = numberArray.indexOf(chosenNumber);
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.
undefined.