简体   繁体   中英

Converting an array to a string in Javascript

I have a multi-dimensional array like this:

1 2 3

4 5 6

Now I need to convert this array into a string like 1,2,3;4,5,6 .

Can any one suggest how to do this, please?

simply use the join method on the array.

> [[1,2,3],[4,5,6]].join(';')
'1,2,3;4,5,6'

It's lucky that you simply don't have to consider how the apply the join method on the inner lists, because a list is joined by comma by default. when a list is coerced into a string, it by default uses commas to separate the items.

As it was already mentioned by qiao, join() is not recursive.
But if you handle the recursion yourself you should acquire the desired result, although in a rather inelegant way.

var array = [[1,2,3],[5,6,7]];
    var result = [];

    array.forEach(
             function(el){
                 result.push(
                      el.join(",")
                 );
             });

    result.join(";");

If you need to serialize an array into a string and then deserialize it later to get an array from the string you might want to take a look at JSON :

http://www.openjs.com/scripts/data/json_encode.php

Try this:

 
 
 
 
  
  
  array.toString();
 
 
  

See here for reference: http://www.w3schools.com/jsref/jsref_tostring_array.asp

  • See answer by qiao for a much nicer approach to multidimensional arrays like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM