所以我有一个看起来像这样的字符串:

123,532,0302,1234等(并且持续不断,有时超过500)。但是,我想将逗号分隔的列表分成40个数组,仅此而已。与PHP中的array_chunk类似(但带有数组)。

实现此目标的最佳方法是什么?

最佳答案

String.prototype.chunk = function(n) {
if (typeof n=='undefined') n=2;
return this.match(RegExp('.{1,'+n+'}','g'));
};

用法示例:
var s = 'abcdefghijklmnopqrstuvwxyz1234';
var a = s.chunk(6);

产量:
var a = ['abcdef','ghijkl','mnopqr','stuvwx','yz1234'];

取自http://javascript.about.com/library/blchunk.htm

编辑:我知道我的第一个答案没有回答问题,所以请看这里:
String.prototype.chunkArr = function (length) {
    var data = this.split(",");
    var result = Array();
    while(data.length > 0) {
        result.push(
            data.splice(0,length)
            .join(",") // comment this or remove line out if you don't want it to re-join into a CSV list of 40 items
        );
    }
    return result;
}

用法示例:
myData = "1,2,3,2,4,5,1,5,1,23,1,23,12,3,12,3,12,3,12,3,12,3,12";
console.log(myData.chunkArr(2)); // Change 2 to 40 if you have longer data

产量:
myData = ["1,2", "3,2", "4,5", "1,5", "1,23", "1,23", "12,3", "12,3", "12,3", "12,3", "12,3", "12"]

如果您注释掉或删除了上面的.join(",")函数中的chunkArr部分(第7行附近),该函数将产生:
myData = [
    ["1", "2"],
    ["3", "2"],
    ["4", "5"],
    ["1", "5"],
    ["1", "23"],
    ["1", "23"],
    //... and so on
]

是的,我知道我可以添加第二个参数来更改“模式” ..但随后出现了惰性:)

10-08 19:24