Thursday, August 31, 2006

 

Addressing Strings as Arrays

I had an eye-0pening shock the other day. I was working on a string that was an exact image of the contents of a text object in my document, except that in the string the "smart quotes" had all been dumbed down. I wanted to write a loop that would look through this string and wherever it encountered a dumb quote, it would set the contents of the corresponding character in the text to the same dumb quote.

So, I could have used charAt(); I could have written a loop that used lastIndexOf; but I wasn't in the mood. It seemed to me that all I had to do was convert the string to an array of single characters and then iterate through the array in the standard way. I intended to write:
myString = myString.split("");
for (var j = myString.length - 1; j >= 0; j--) {
if (myString[j] == "'" || myString[j] == '"') {
myText.characters[j].contents = myString[j];
}
}
So I tested it and saw that it had worked and all was well and peace descended on my soul.

But then I had a heart-stopping realization. I'd forgotten to include that first statement which converts myString to an array. What! How did the script work if I'd made this mistake?

It turns out that you don't need charAt() to read the characters of a string. You can read them by addressing them as though they were members of an array. But this is the only thing you can do in this fashion. If you try to set a character this way it won't work. If you try to sort the characters, it won't work. But if all you want to do is read the individual characters, it works like a charm!

This page is powered by Blogger. Isn't yours?