I am trying to use .indexOf to find out if an array contains a string. Something is causing an error, but I don't know what. I'm sure this is a really simple thing, but I don't know the language and so don't see it. What's wrong?
//this code creates an error in IE
var myMines=new Array();
var newMine="22";
var myVar = myMines.indexOf(newMine); //when I comment out this line, the page does not generate an error
Are you, by chance, using IE 8 (or lower)? Array.indexOf
only works in IE 9+, Firefox 3+, and Chrome 7+.
Source: http://kangax.github.com/es5-compat-table/
Docs for Array.indexOf
(also includes a function to implement this in browsers that don't support it): https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
Before being added in some modern browsers indexOf was exclusively a function used to search a string for another string and return the starting index. You are trying to use this function on an empty array and I'm guessing in a browser that does not support the indexOf function for arrays.
indexOf
was added for arrays. https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexO - Rocket Hazmat 2012-04-04 17:47
All you are doing it creating an array, and then seeing if something exists in it.
newMine is simply a value that you are attempting to look for inside an empty array. Try populating the array first.
indexOf
on a blank array will return -1, not an error - Rocket Hazmat 2012-04-04 17:47
What you do is basically:
I've just posted your code into my Firebug console (running Firefox 11) and it worked. As your array is "empty" here, indexOf() just returns -1. Maybe you're script just can't handle a -1 value. However, I believe this code should work in most browsers. Who knows, maybe you've just found a bug in chrome's javascript implementation (^^).
The IndexOf
returns the current index/position (0 base) of a string, i.e.
var myMines="Hello World";
var myVar = myMines.indexOf('W');
alert(myVar); // Will alert 6 because 'W' is at the 7th position (first index is 0) so index is 6
indexOf
was added for arrays. https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexO - Rocket Hazmat 2012-04-04 17:51
indexOf
work, but it shouldn't matter to us JavaScript programmers - Rocket Hazmat 2012-04-04 18:01
indexOf
for arrays - kirilloid 2012-04-04 17:45