所以我有一个看起来像这样的字符串:
123,532,0302,1234等等(它一直持续,有时超过500)。但是,我想将逗号稀释列表拆分为40个数组,仅此而已。类似于PHP中的array_chunk(但有数组)。
实现这一目标的最佳方法是什么?
答案 0 :(得分:4)
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
]
是的,我知道我可能只是添加了第二个参数来改变'模式'..但随之而来的是懒惰:)
答案 1 :(得分:0)
如果我正确理解了所需的输出,你可以拆分所有的逗号,然后将生成的长数组分成几个不超过40的数组。
function splitChunkIntoArrays(data, chunkLength) {
var temp = data.split(",");
var output = [];
var item = [];
for (var i = 0; i < temp.length; i++) {
// if item is now full, put it into the result and start a new chunk
if (item.length == chunkLength) {
output.push(item);
item = [];
}
item.push(temp[i]);
}
// if anything in the last chunk, put it in the result
if (item.length != 0) {
output.push(item);
}
return(output);
}
// sample output from splitChunkIntoArrays:
[
[1,2,3,4,..40],
[41,42,43,...80],
[81,82,83,...120],
[121,123,124]
]
这将为您提供一个数组数组,其中每个内部数组的长度不超过chunkLength项。
如果您希望生成的40项长项仍然是字符串(在您的问题中并不完全清楚),那么您可以再次加入内部数组:
function splitChunkIntoStrings(data, chunkLength) {
var splitData = splitChunkIntoArrays(data, chunkLength);
var results = [];
for (var i = 0; i < splitData.length i++) {
results.push(splitData[i].join(","));
}
return(results);
}
// sample output from splitChunkIntoStrings:
[
"1,2,3,4,..40",
"41,42,43,...80",
"81,82,83,...120",
"121,123,124"
]
这会产生一个字符串数组,其中每个字符串都有40个或更少的逗号分隔值。
而且,这是使用数组splice()
的第一个函数的更精简版本:
function splitChunkIntoArrays(data, chunkLength) {
var temp = data.split(","), result = [];
while (temp.length > 0) {
result.push(temp.splice(0, chunkLength));
}
return(result);
}
或者如果您希望结果仍为字符串,则可以执行以下操作:
function splitChunkIntoStrings(data, chunkLength) {
var temp = data.split(","), result = [];
while (temp.length > 0) {
result.push(temp.splice(0, chunkLength).join(","));
}
return(result);
}