Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array to string in NodeJS

Tags:

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?

like image 699
Magic Avatar asked Jan 18 '12 08:01

Magic


People also ask

How do I convert an array to a string in node JS?

toString is a method, so you should add parenthesis () to make the function call. 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.

How do you turn an array into a string?

Using StringBuffer Create an empty String Buffer object. Traverse through the elements of the String array using loop. In the loop, append each element of the array to the StringBuffer object using the append() method. Finally convert the StringBuffer object to string using the toString() method.

Which method converts an array to string in JavaScript?

toString() The toString() method returns a string representing the specified array and its elements.


1 Answers

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(",") 
like image 133
Dominic Barnes Avatar answered Oct 09 '22 07:10

Dominic Barnes