Javascript indexOf – String vs Array
As of Javascript 1.6 indexOf() is a method available for use with Arrays. However, there’s one subtle difference when operating on a String and an Array, both are case sensitive, Array.indexOf() is type sensitive. This is documented but for those of you who’ve not bothered with the documentation, and it’s not working as expected, here’s a heads up on a subtle gotcha…
<script type="text/javascript">
var list = new Array("1",2,"3",4,"5");
console.log("Index of 1: " + list.indexOf(1));
console.log("Index of 2: " + list.indexOf(2));
console.log("Index of 3: " + list.indexOf(3));
console.log("Index of 4: " + list.indexOf(4));
console.log("Index of 5: " + list.indexOf(5));
var jist = list.join(",");
console.log("Index of 1: " + jist.indexOf(1));
console.log("Index of 2: " + jist.indexOf(2));
console.log("Index of 3: " + jist.indexOf(3));
console.log("Index of 4: " + jist.indexOf(4));
console.log("Index of 5: " + jist.indexOf(5));
</script>
Viewing the debug output in Firebug we can see the type checking; the string elements in the array are not found. Concatenate the array to a string and perform the same check – it’s now type insensitive.

This entry was posted on Wednesday, 6th January, 2010 at 17:10 and is filed under JavaScript, Tech Talk.
You can follow any responses to this entry through the RSS 2.0 feed.
You can skip to the end and leave a response. Pinging is currently not allowed.
You can skip to the end and leave a response. Pinging is currently not allowed.


