我有一个字符串,看起来像这样:
123,532,0302,1234等等(并且它继续下去,有时超过500)。但是,我想将逗号分隔的列表拆分为40个元素的数组,不多也不少。类似于PHP中的array_chunk(但使用的是数组)。
如何最好地实现这一点?
我有一个字符串,看起来像这样:
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'];
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"]
chunkArr
函数中注释或删除.join(",")
部分(大约在第7行左右),该函数将产生以下结果:myData = [
["1", "2"],
["3", "2"],
["4", "5"],
["1", "5"],
["1", "23"],
["1", "23"],
//... and so on
]
是的,我知道我可以添加第二个参数来改变“模式”,但由于懒惰所致,我没有这样做 :)
splice
而不是另一个内部循环也更简单。 - Seth Malaki如果我正确理解所需的输出,您可以在所有逗号上拆分,然后将结果长数组分成多个不超过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"
]
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);
}
splice
创建了相同的输出,但使它更简单了。 - Seth Malaki