开发者

Splitting to 2D array

How I can split a string into 2D array. String开发者_运维知识库 is like

1c2c3r4c5c6r6c8c9

array should be like

[[1,2,3],
[4,5,6],
[7,8,9]]


var src = "1c2c3r4c5c6r6c8c9";
var rows = src.split(/r/);

for (var i = 0; i < rows.length; i++)
    rows[i] = rows[i].split(/c/);

Please note that I didn't test this so it might contain a syntax error or something...


You can use the map method on Array

var s = "1c2c3r4c5c6r6c8c9";
var rows = s.split("r");
result = rows.map(function (x) {
    return x.split('c');
}));

map is introduced in ECMAScript5 and is not supported in older browsers. But, there is a decent work-around here


var str = "1c2c3r4c5c6r6c8c9";
var result = [];
var group = str.split("r");
for(i in group) {result.push(group[i].split("c"))};

result should be what you want.


This should work:

var src = "1c2c3r4c5c6r6c8c9";
var rows = src.split(/r/g);

for (var i = 0; i < rows.length; i++) {
    var cells = rows[i].split(/c/g);
    for (var j = 0; j < cells.length; j++) {
        cells[j] = parseInt(cells[j]);
    }
    rows[i] = cells;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜