So last night I was bitten by a very unexpected behavior in the IE JavaScript engine (IE7, specifically, but I would suspect it’s present in all the other versions).
Background
I have a function that iterates through the characters in a string trying to align them with those from another string. I was doing this with a for loop from 0 through “length – 1” and then pulling out the pertinent character from the string using the indexer, e.g.
for (var c = 0; c < myString.length; c++) { alert("char at index " + c + " was: " + myString[c]); } Problem
This seemed to work fine in all of my initial tests and works like a charm in Firefox. However, when I flipped back to IE7 to run my JSUnit tests there as well, I saw about 7 errors in my results. Turns out it was an error from when the string was a single character, e.g. “x”. From an object perspective, JavaScript still knows it’s a string because all of the string methods are available. However, use of the indexer, e.g. myString[c], caused it to blow up, saying that myString[c] was undefined.
My assumption here is that, in IE, the indexer syntax actually tries to retrieve the index from its internal data structure (i.e. char[]) rather than its JS representation (i.e. String). However, it seems that when the string is only one character long, its internal representation is just a plain ole char rather than a char array. Very odd!
Solution/Workaround
Any which way, this was easily worked around by using the string methods instead:
for (var c = 0; c < myString.length; c++) { alert("char at index " + c + " was: " + myString.substring(c, c + 1)); }