简体   繁体   English

在Javascript中将数组转换为字符串

[英]Converting an array to a string in Javascript

I have a multi-dimensional array like this: 我有一个这样的多维数组:

1 2 3 1 2 3

4 5 6 4 5 6

Now I need to convert this array into a string like 1,2,3;4,5,6 . 现在,我需要将该数组转换为1,2,3;4,5,6类的字符串。

Can any one suggest how to do this, please? 请问有人可以建议如何做吗?

simply use the join method on the array. 只需在数组上使用join方法。

> [[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. 幸运的是,您不必考虑如何在内部列表上应用join方法,因为 默认情况下列表是用逗号连接的。 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. 正如qiao已经提到的那样, join()不是递归的。
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 : 如果需要将数组序列化为字符串,然后稍后反序列化以从字符串中获取数组,则可能需要看一下JSON

http://www.openjs.com/scripts/data/json_encode.php 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 请参阅此处以供参考: http : //www.w3schools.com/jsref/jsref_tostring_array.asp

  • See answer by qiao for a much nicer approach to multidimensional arrays like this. 有关这种多维数组的更好方法,请参见qiao的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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