我已将JavaScript spritesheet转换为2D整数数组,现在我正在尝试将2D整数数组拆分为多个2D数组,使用1作为“分隔符”数字。
有没有办法使用分隔符号将如下所示的2D JavaScript数组分成多个数组,如下所示?
function separate2DArray(arrToSeparate, separator){
//separate the 2D array into multiple 2D arrays, using a
//specific number as the separator
}
//array to separate:
[
[5, 5, 5, 1, 5, 4, 5],
[5, 5, 4, 1, 4, 3, 4],
[1, 1, 1, 1, 1, 1, 1], //1 is the "separator number", which splits the array
[9, 2, 1, 4, 2, 4, 5], //horizontally and vertically
]
//The array above would produce the following 2D arrays:
5 5 5
5 5 4
5 4 5
4 3 4
9 2
4 2 4 5
我想到的这个算法的主要应用是spritesheet图像分离。
答案 0 :(得分:1)
鉴于分隔区域是矩形,这将起作用:
function separate2DArray(array, sep){
//separate the 2D array into multiple 2D arrays, using a
//specific number as the separator
var result = [],
currentSubs = {}; // using x coordinate as key
for (var y=0; y<array.length; y++) {
var line = array[y],
subBegin = 0;
for (var x=0; x<=line.length; x++) {
if (x == line.length || line[x] == sep) {
if (subBegin < x) {
var sub = line.slice(subBegin, x);
if (subBegin in currentSubs)
currentSubs[subBegin].push(sub);
else
currentSubs[subBegin] = [sub];
} else { // a line of separators, subBegin == x
if (subBegin in currentSubs) {
result.push(currentSubs[subBegin]);
delete currentSubs[subBegin];
}
}
subBegin = x+1;
}
}
}
for (var begin in currentSubs)
result.push(currentSubs[begin]);
return result;
}
这里的结果只是一个非常简单的子区域数组,没有任何关于它们在原始区域中的位置的信息。改进版本:
function separate2DArray(array, sep){
var result = [],
currentSubs = {};
for (var y=0; y<array.length; y++) {
var line = array[y],
subBegin = 0;
for (var x=0; x<=line.length; x++) {
if (x == line.length || line[x] == sep) {
if (subBegin < x) {
var subline = line.slice(subBegin, x);
if (! (subBegin in currentSubs)) {
var subarea = [];
result.push({x:x, y:y, area:subarea});
currentSubs[subBegin] = subarea;
}
currentSubs[subBegin].push(subline);
} else {
if (subBegin in currentSubs)
delete currentSubs[subBegin];
}
subBegin = x+1;
}
}
}
return result;
}
答案 1 :(得分:0)
您必须遍历数组,每当找到1
时将预览条目捕获到子数组中 var arr = [[5, 5, 5, 1, 5, 4, 5], [5, 5, 4, 1, 4, 3, 4], [1, 1, 1, 1, 1, 1, 1], [9, 2, 1, 4, 2, 4, 5]];
var twoD = [];
for (var x = 0; x < arr.length; x++) {
var row = arr[x];
var subArray = [], subArrays=[];
for (var y = 0; y < row.length; y++) {
if (row[y] == 1) {
if (subArray.length) subArrays.push(subArray.slice(0));
subArray = [];
}
else {
subArray.push(row[y]);
}
}
if (subArray.length) subArrays.push(subArray);
if(subArrays.length) twoD.push(subArrays);
}
console.log(twoD);
document.write(JSON.stringify(twoD));