As with objects, arrays have same methods for data conversion. These are: toLocaleString, toString() and valueOf().

The methods toString() and valueOf() return same values. Observe following example:

var names = ["Joe", "Allen", "Wrench"];

alert(names.toString()); // Joe, Allen, Wrench

alert(names.valueOf()); // Joe, Allen, Wrench

alert(names); // Joe, Allen, Wrench

In the last example, the alert command converts "names" first into a string; the result is identical as in other two examples above.

In the case of toLocaleString() conversion the result will be equal as those two from above. The only difference is that this method will try to detect locale conventions that might be defined on that particular PC, system or browser.

It may be very useful with numbers representation, or dates; as shown in the example below.

Considering that these methods return the arrays items as a comma-separated string, it is possible to construct a string with a different separator.

To change the separator (delimiter) a method join may be used. This method accepts one argument and that is the string separator to be used. For instance:

var color = ["yellow", "red", "pink"];

alert (colors); // yellow,red,pink

alert (colors.join("/")); // yellow/red/pink

Example

The example with array conversion methods in JavaScript:

 

›› go to examples ››