advertisement -- please support sponsors

programming:
converting objects to strings

I want to load a document's URL into a string, massage it and then reload the frame with the new document.To start, I store the windows's location in a string by saying:var aString = parent.mainWindow.location;After that I want to get access to it's length to start a for loop:for (i-0;i<aString.length;i++)....but this statement bombs telling me "undefined is not a number"Any comments?

Consider both of the following JavaScript programs. One of them works and one of them doesn't. Can you guess which one?

Program A Program B
url = window . location;
for (i = 0; i < url . length; ++ i)
	document . write (url . charAt (i));
url = window . location + "";
for (i = 0; i < url . length; ++ i)
	document . write (url . charAt (i));

At first glance, it would seem like both programs output the current document's URL, one character at a time. In Program A, however, url is assigned a Location object, rather than a String object, so that the expression url . charAt (i) causes an error.

The value of window . location must be explicitly converted to a string before it can be treated like a string. In JavaScript, you can convert many data types to strings simply by adding other strings to them. In most cases, it is sufficient to add an empty string, or "". That's what I did in Program B, and that's why program B works, while Program A does not.

Charlton Rose
29 August 1997