use Conversion methods in an array to convert
Description
The inherited methods toLocaleString(), toString(), and valueOf() each return the array items as a comma-separated string.
The toString() and valueOf() methods return the same value when called on an array.
The result is a comma-separated string that contains the string equivalents of each value in the array.
Example
/*from w ww . j ava 2 s.co m*/
var colors = ["red", "blue", "green"]; //creates an array with three strings
console.log(colors.toString()); //red,blue,green
console.log(colors.valueOf()); //red,blue,green
console.log(colors); //red,blue,green
The code above generates the following result.
toLocaleString
toLocaleString() calls each item's toLocaleString() instead of toString() to get its string value.
var person1 = {/*w ww. ja v a 2s . c om*/
toLocaleString : function () {
return "toLocaleString 1";
},
toString : function() {
return "toString 1";
}
};
var person2 = {
toLocaleString : function () {
return "toLocaleString 2";
},
toString : function() {
return "toString 2";
}
};
var people = [person1, person2];
console.log(people);
console.log(people.toString());
console.log(people.toLocaleString());
Separator
To construct a string with a different separator, use the join() method.
The join() method accepts the string separator as the parameter, and returns a string containing all items.
var colors = ["red", "green", "blue"];
console.log(colors.join(",")); //red,green,blue
console.log(colors.join("||")); //red||green||blue
The code above generates the following result.
Note
If an item in the array is null or undefined, it is represented by an empty string in the result of join(), toLocaleString(), toString(), and valueOf().