包含逗号的数组到字符串 - JavaScript

Par*_*xis 6 javascript arrays jquery

好的,我正在编写一个包含完整句子的脚本,但整个句子可以包含逗号.

由于脚本的工作方式,数组必须至少转换为一次字符串.因此,当发生这种情况时,一旦我将字符串拆分回原始值,逗号的开始就会相互冲突.

我无法弄清楚如何解决这个问题,到目前为止我一直在寻找并没有成功.

我正在使用chrome插件,这是发生的事情的一个小例子:

var Data = ["This is a normal string", "This string, will cause a conflict.", "This string should be normal"];

// The data gets sent to a background script, in string form and comes back as this
var Data = "This is a normal string, This string, will cause a conflict., This string should be normal";
Data = Data.split(",");

// Results in 4 positions instead of 3
Data = ["This is a normal string", "This string"," will cause a conflict.", "This string should be normal"];
Run Code Online (Sandbox Code Playgroud)

Ben*_*aum 5

当您调用.join()数组以将其转换为字符串时,您可以指定分隔符。

例如:

["Hello,","World"].join("%%%"); // "Hello,%%%World"
Run Code Online (Sandbox Code Playgroud)

然后,您可以根据"%%%"( .split("%%%"))将其拆分,以便再次将其拆分。

这就是说,如果你想一个动作应用于阵列(每行)中的每个元素,你可能没有打电话.join,然后.split它一次。相反,您可以使用数组方法,例如:

 var asLower = ["Hello","World"].map(function(line){ return line.toLowerCase(); });
 // as Lower now contains the items in lower case
Run Code Online (Sandbox Code Playgroud)

或者,如果您的目标是序列化而不是处理 - 您不应该“推出自己的”序列化并使用建议的内置JSON.parseJSON.stringify方法,如 h2oooooo。