简体   繁体   English

将具有特殊字符的数组转换为字符串

[英]Convert array with special character to string

i have the below array:我有以下数组:

let arr= ["5,5", "Orange", "6,1"];

Every item in that arr is random string and contains any character ( "," , ";" ,...")该 arr 中的每个项目都是随机字符串并包含任何字符( ","";" ,...“)

For some reasons, i have to convert arr to string.由于某些原因,我必须将arr转换为字符串。

I used let s = arr.toString() and got the string: s= "5,5,Orange,6,1"我用let s = arr.toString()得到了字符串: s= "5,5,Orange,6,1"

The problem is: I have to convert that string back to the array without reusing arr and losing the format.问题是:我必须将该字符串转换回数组而不重用arr并丢失格式。 If i use string.split(",") , the result is ["5", "5", "Orange", "6", "1"] instead of ["5,5", "Orange", "6,1"]如果我使用string.split(",") ,结果是["5", "5", "Orange", "6", "1"]而不是["5,5", "Orange", "6,1"]

i know toString() is the same to join array with "," , but if i use arr.join() with other character then split() , it seems silly because item in arr is random and can contain any character.我知道toString()","连接数组是相同的,但是如果我将arr.join()与其他字符一起使用然后split() ,这似乎很愚蠢,因为 arr 中的项目是随机的并且可以包含任何字符。

Thanks a lot!非常感谢!

This is what JSon is for.这就是 JSon 的用途。

 let arr= ["5,5", "Orange", "6,1"]; let arrStr = JSON.stringify(arr); console.log('arrStr: ', arrStr, 'as string'); let newArr = JSON.parse(arrStr); console.log('newArr:', newArr);

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

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