about me about me
photography photography
software projects software projects
contact me contact me

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.

Firebug debug output

comments

No comments for this post.

this post's tags