将数组转换为字符串Javascript
在拆分函数中未找到解决方案。。 我试图将字符串转换为数组。。 这根绳子就像将数组转换为字符串Javascript,javascript,arrays,string,Javascript,Arrays,String,在拆分函数中未找到解决方案。。 我试图将字符串转换为数组。。 这根绳子就像 My name-- is ery and your-- is this 我只想将该字符串转换为数组,然后将其打印出来,但在得到这个'--'时,也要断开该行 到目前为止,我已经做到了 function listToAray(fullString, separator) { var fullArray = []; if (fullString !== undefined) { if (fullString
My name-- is ery and your-- is this
我只想将该字符串转换为数组,然后将其打印出来,但在得到这个'--'时,也要断开该行
到目前为止,我已经做到了
function listToAray(fullString, separator) {
var fullArray = [];
if (fullString !== undefined) {
if (fullString.indexOf(separator) == -1) {
fullAray.push(fullString);
} else {
fullArray = fullString.split(separator);
}
}
return fullArray;
}
但对于字符串中以逗号分隔的单词,但我想要的是将字符串转换为数组,然后在getiing'--'这是数组上断行时将其打印出来
提前感谢似乎有效:
text = "My name-- is ery and your-- is this";
function listToAray(fullString, separator) {
var fullArray = [];
if (fullString !== undefined) {
if (fullString.indexOf(separator) == -1) {
fullAray.push(fullString);
} else {
fullArray = fullString.split(separator);
}
}
return fullArray;
}
console.log(listToAray(text,"--"));
控制台输出:
["My name", " is ery and your", " is this"]
你期待什么 您可以使用
split
方法:
var str = "My name-- is ery and your-- is this";
var res = str.split("--");
console.log(res);
// console output will be:
["My name", " is ery and your", " is this"]
你为什么要做这么复杂的事?有一个
.split()
方法允许您在一行代码中执行此操作:
text = "My name-- is ery and your-- is this";
array = text.split('--');
> ["My name", " is ery and your", " is this"]
现在,如果要在--
上断线,可以执行以下操作:
text = "My name-- is ery and your-- is this";
list = text.replace(/\-\-/g, '\n');
console.log(list);
> "My name
is ery and your
is this"
问题标题提到了另一种方式。事实上,您只能使用
fullArray=fullString.split(分隔符)代码>在if
语句中,因为如果字符串中没有分隔符,split
函数无论如何都会将字符串转换为数组