Main Page

toString

The
Array
object overrides the
toString()
and
valueOf()
methods to return a special string. This
string is made by calling the
toString()
method on each item in the array and then combining them
using commas. For example, an array with the items
“red”
,
“green”
, and
“blue”
return the string
“red,green,blue”
when either of the methods is called.
var aColors = [“red”, “green”, “blue”];
alert(aColors.toString()); //outputs “red,green,blue”
alert(aColors.valueOf()); //outputs “red,green,blue”
Similarly, the
toLocaleString()
method returns a string made up of the items in the array. The one
difference here is that each of the items’
toLocaleString()
methods is called to get the value. In many
cases, this returns the same value as
toString()
, with the strings joined by commas.
var aColors = [“red”, “green”, “blue”];
alert(aColors.toLocaleString()); //outputs “red,green,blue”
Because developers may also want to create such values out of arrays, ECMAScript provides a method
called
join()
, whose sole purpose it is to create concatenated string values. The
join()
method accepts
one argument, which is the string to use between the items. Consider the following example:
var aColors = [“red”, “green”, “blue”];
alert(aColors.join(“,”)); //outputs “red,green,blue”
alert(aColors.join(“-spring-”)); //outputs “red-spring-green-spring-blue”
alert(aColors.join(“][“)); //outputs “red][green][blue”
Here, the
join()
method is used to create three different string representations of the array. The first,
using the comma, is essentially equal to calling the
toString()
or
valueOf()
method; the second and
third use different strings to create odd (and probably not that useful) separators between the array
items. The point to understand is that any string can be used as a separator.
You may be wondering at this point, if the
Array
has a way to convert itself into a string, does the
String
have a way to convert itself into an array? The answer is yes. The
String
class has a method
called
split()
that does exactly that. The
split()
method takes only one parameter. That parameter,
as you probably guessed, is the string that should be considered the separator between items. So, if you
have a string separated by commas, you can do the following to convert it into an
Array
:
var sColors = “red,green,blue”;
var aColors = sColors.split(“,”);
If you specify an empty string as the separator, the
split()
method returns an array in which each item
is equal to one character in the string, for example:
var sColors = “green”;
var aColors = sColors.split(“”);
alert(aColors.toString()); //outputs “g,r,e,e,n”
Here, the string
“green”
is transformed into an array of the strings
“g”
,
“r”
,
“e”
,
“e”
, and
“n”
. This
functionality can be useful if you need to parse strings character-by-character.
72
Chapter 3
06_579088 ch03.qxd 3/28/05 11:36 AM Page 72


JavaScript EditorFree JavaScript Editor     Ajax Editor


©