Gabriel Petrovay
Gabriel Petrovay

Reputation: 21944

How to make Array.toString() in IE9 compatible with modern browsers

I want to assign an array value to an attribute in DOM:

var myArray = [1, 2, 3];
elem.setAttribute('value', myArray)

in modern browsers you have the result:

<input value="1,2,3">

but in older ones (up to IE9):

<input value="[object]">

JSON.stringify is not a solution because this will generate:

<input value="[1,2,3]">

The problem is that myArray.toString() in modern browsers outputs:

1,2,3

while in older ones:

[object]

How can I solve this?

Upvotes: 3

Views: 520

Answers (2)

Kyle Muir
Kyle Muir

Reputation: 3925

If you're intent on having the toString method, you could overwrite it like this:

var myArray = [1, 2, 3];

Array.prototype.toString = function () {
    return this.join(', ');
}

console.log(myArray.toString()); //1, 2, 3

This should work in most older browsers.

Fiddle: http://jsfiddle.net/KyleMuir/KUzZL/

Upvotes: 1

Ionică Bizău
Ionică Bizău

Reputation: 113495

Use JSON.stringify(array) instead of .toString(). Also, you can write a function like this that will convert your array to string.

function arrayToString(array) {
   var arrayStr = JSON.stringify([1, 2, 3]);
   arrayStr = arrayStr.substring(1);
   arrayStr = arrayStr.substring(0, arrayStr.length -1);
   return arrayStr;
}

or even shortener:

var str = array.join(",");

Example:

arrayToString([1, 2, 3, 4]); // returns "1, 2, 3, 4"

Also, you can extend the prototype of Array overwriting the toString() function:

Array.prototype.toString = function () {
    return this.join(",");
}

Upvotes: 0

Related Questions