将多个数组转换为字符串并用逗号连接它们
Posted
技术标签:
【中文标题】将多个数组转换为字符串并用逗号连接它们【英文标题】:convert multiple array into string and concat them with comma 【发布时间】:2021-09-14 16:13:36 【问题描述】:我在一个数组中有一组数组,我想在数组内部进行转换,并用逗号和双引号分隔它,以便区分。
example:
var arr1 = [1,2,3,4,5,6,7,8,9,10];
var arr2 = [11,12,13,14,15,16,17,18,19,20];
var arr3 = [21,22,23,24,25,26,27,28,29,30];
var arr4 = [31,32,33,34,35,36,37,38,39,40];
this should converted and out should be
array["1,2,3,4,5,6,7,8,9,10","11,12,13,14,15,16,17,18,19,20","21,22,23,24,25,26,27,28,29,30","31,32,33,34,35,36,37,38,39,40"]
到目前为止我所做的是
var converArr1 = String(arr1);
var converArr2 = String(arr2);
var converArr3 = String(arr3);
var converArr4 = String(arr4);
var finalString = converArr1.concat(converArr2);
finalString = finalString.concat(converArr3);
finalString = finalString.concat(converArr4);
this is not concating it with double qoute
【问题讨论】:
您希望结果是 4 个字符串的数组,还是希望结果是字符串:array["1,2,3,4,5,6,7,8,9,10","11,12,13,14,15,16,17,18,19,20","21,22,23,24,25,26,27,28,29,30","31,32,33,34,35,36,37,38,39,40"]
?
我希望结果是 4 个字符串的数组
查看我的答案的编辑。
这个要求似乎很奇怪。出于什么原因,您可能希望将子数组转换为字符串?这让他们更难合作。因此,这似乎是一个 XY 问题。
【参考方案1】:
从数组映射到数组的字符串表示形式(用引号括起来),然后用逗号 (,
) 连接这些字符串表示形式,然后使用模板文字将 array[]
括起来。
var arr1 = [1,2,3,4,5,6,7,8,9,10];
var arr2 = [11,12,13,14,15,16,17,18,19,20];
var arr3 = [21,22,23,24,25,26,27,28,29,30];
var arr4 = [31,32,33,34,35,36,37,38,39,40];
let result = "";
result = `array[$[arr1, arr2, arr3, arr4].map(arr => `"$String(arr)"`).join(",")]`;
console.log(result);
如果您希望结果是 4 个字符串的数组:
var arr1 = [1,2,3,4,5,6,7,8,9,10];
var arr2 = [11,12,13,14,15,16,17,18,19,20];
var arr3 = [21,22,23,24,25,26,27,28,29,30];
var arr4 = [31,32,33,34,35,36,37,38,39,40];
let result = "";
result = [arr1, arr2, arr3, arr4].map(arr => String(arr));
console.log(result);
【讨论】:
以上是关于将多个数组转换为字符串并用逗号连接它们的主要内容,如果未能解决你的问题,请参考以下文章