And*_*een 2 javascript string split
在JavaScript中,是否可以使用分隔符在多维字符串数组中拆分每个字符串?我正在尝试使用字符串分隔符拆分多维数组的字符串,但我还不知道如何在不使用多个for循环的情况下迭代多维数组.
var theArray = [["Split,each"],["string, in"],["this, array"]];
Run Code Online (Sandbox Code Playgroud)
据我所知,不可能将该string.split(",")方法应用于多维数组.我需要找到一种解决方法,因为此代码无效:
alert([["Split,each"],["string, in"],["this","array"]].split(","));
Run Code Online (Sandbox Code Playgroud)
使用Array map方法返回数组的修改版本:
var newArray = theArray.map(function(v,i,a){
return v[0].split(",");
});
Run Code Online (Sandbox Code Playgroud)
作为参数传递给map方法的函数用于确定映射数组中的值.如您所见,该函数获取数组中的每个值,用逗号分隔它,并返回两个字符串的结果数组.
输出是:
[["Split", "each"],["string", "in"],["this", "array"]];
Run Code Online (Sandbox Code Playgroud)
要为任意深度的数组递归地执行此工作,您可以使用:
var newArray = theArray.map(function mapper(v,i,a){
if(typeof v == "string"){
return v.split(",");
} else {
return v.map(mapper);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3533 次 |
| 最近记录: |