[node.js] Convert array to string in NodeJS

I want to convert an array to string in NodeJS.

var aa = new Array();
aa['a'] = 'aaa';
aa['b'] = 'bbb';

console.log(aa.toString());

But it doesn't work.
Anyone knows how to convert?

This question is related to node.js

The answer is


You're using an Array like an "associative array", which does not exist in JavaScript. Use an Object ({}) instead.

If you are going to continue with an array, realize that toString() will join all the numbered properties together separated by a comma. (the same as .join(",")).

Properties like a and b will not come up using this method because they are not in the numeric indexes. (ie. the "body" of the array)

In JavaScript, Array inherits from Object, so you can add and delete properties on it like any other object. So for an array, the numbered properties (they're technically just strings under the hood) are what counts in methods like .toString(), .join(), etc. Your other properties are still there and very much accessible. :)

Read Mozilla's documentation for more information about Arrays.

var aa = [];

// these are now properties of the object, but not part of the "array body"
aa.a = "A";
aa.b = "B";

// these are part of the array's body/contents
aa[0] = "foo";
aa[1] = "bar";

aa.toString(); // most browsers will say "foo,bar" -- the same as .join(",")

toString is a method, so you should add parenthesis () to make the function call.

> a = [1,2,3]
[ 1, 2, 3 ]
> a.toString()
'1,2,3'

Besides, if you want to use strings as keys, then you should consider using a Object instead of Array, and use JSON.stringify to return a string.

> var aa = {}
> aa['a'] = 'aaa'
> JSON.stringify(aa)
'{"a":"aaa","b":"bbb"}'

toString is a function, not a property. You'll want this:

console.log(aa.toString());

Alternatively, use join to specify the separator (toString() === join(','))

console.log(aa.join(' and '));

You can also cast an array to a string like...

newStr = String(aa);

I also agree with Tor Valamo's answer, console.log should have no problem with arrays, no need to convert to a string unless you're debugging something or just curious.


In node, you can just say

console.log(aa)

and it will format it as it should.

If you need to use the resulting string you should use

JSON.stringify(aa)