4

我一直在寻找一种更简洁的方式来表示 Javascript 中的多维数组,所以我想找到一种使用多个分隔符来分隔数组的方法,以及 Javascript 的内置string.split(separator)方法。

例如,字符串"what, am, I; doing, here, now"将变为[["what", "am", "I"],["doing", "here", "now"]].

是否有任何简洁的方法来实现执行此操作的功能?

var theString = "what, am, I; doing, here, now";
var theArray = getArray(theString, [",", ";"]); //this should return [["what", "am", "I"],["doing", "here", "now"]].

function getArray(theString, separators){
    //convert a string to a multidimensional array, given a list of separators
}
4

3 回答 3

7

最后编辑

正如@Tom 指出的那样,我在单词中留下了一些逗号。这是最终的代码:

var str = "what, am, I; doing, here, now";

var arr = str.split(/\;\s*/g);
for (var i = 0; i < arr.length; i++){
    arr[i] = arr[i].split(/\,\s*/g);
}
console.log(arr);

和小提琴


首先在第二个分隔符上拆分,然后在另一个分隔符上拆分其中的每个成员。

var str = "what, am, I; doing, here, now";

var arr = str.split(';');
for (var i = 0; i < arr.length; i++){
    arr[i] = arr[i].split(' ');
}

现场演示

请注意,您必须进行一些清理以删除第二个数组中的空白空间,但这应该很简单。


编辑——我感觉精力充沛——这就是你如何杀死那个烦人的领先空间

var str = "what, am, I; doing, here, now";

var arr = str.split(';');
for (var i = 0; i < arr.length; i++){
    arr[i] = arr[i].replace(/^\s*/, '').split(' ');
}

更新的小提琴


编辑——这就是我如此爱的原因。根据@Nathan,您可以拆分正则表达式并省去一些麻烦

var str = "what, am, I; doing, here, now";

var arr = str.split(/\;\s*/g);
for (var i = 0; i < arr.length; i++){
    arr[i] = arr[i].split(' ');
}
console.log(arr);

更新的小提琴

于 2012-12-08T06:30:16.013 回答
1

这应该有效:

var theString = "what, am, I; another, string; doing, here, now";
 //this should return [["what", "am", "I"],["doing", "here", "now"]].

function getArray(theString, separators){
    //Firs split
    var strings = theString.replace(/\s+/g, '').split(separators.pop());
    //Second split
        var sep = separators.pop();
        for (var i = 0; i < strings.length; i++) {
            strings[i] = strings[i].split(sep);
        };
    console.log(strings);
    return strings;
}

var theArray = getArray(theString,["," ,";" ]);

更新:

现在代码应该可以工作了:http: //jsfiddle.net/beTEq/1/

于 2012-12-08T06:46:59.443 回答
0

根据这里的答案,我想出了一个可以处理任意数量的分隔符的解决方案

function getArray(theString, separators) {
    separators = separators.reverse();
    var theArray = theString.split(separators[0]);
    for (var j = 1; j < separators.length; j++) {
        theArray = theArray.map(function mapper(v, i, a) {
            if (typeof v == "string") {
                return v.split(separators[j]);
            } else {
                return v.map(mapper);
            }
        });
    }
    return theArray;
}

console.log(JSON.stringify(getArray("A, b, c; d, e, f;g,h,i'a, b, c;d,e,f", [",", ";", "'"])));
//this will write [[["A"," b"," c"],[" d"," e"," f"],["g","h","i"]],[["a"," b"," c"],["d","e","f"]]] to the console.
于 2013-05-12T04:20:46.770 回答