我有數據中的數據填充到表中。陣列的索引對應於表中的點,如下所示:轉換表索引
0,1,2 0,1,2 0,1,2
3,4,5 or 3,4,5 or 3,4,5
6,7,8 6,7 6
也就是說從左到右,從上到下排列。我需要想出一個函數,從上到下,從左到右排列它。像這樣:
0,3,6
1,4,7
2,5,8
有幾件事要注意。該表可以包含任意數量的元素,但只會有3列。
所以總結一下,我需要的是這樣的:
Array indexes = [0,1,2,3,4,5,6,7,8]
Indexes after converting= [0,3,6,1,4,7,2,5,8]
現在我這個工作有些情況下,就像如果有九個值。我只是真的很難找出任意案件。即時通訊使用Javascript,但任何語言的任何答案真的會有所幫助。
對此的推理,是我需要我的表放置不同,但不想觸摸html。我想重新排序索引,以便從上到下,從左到右排列。
繼承人是我到目前爲止有:
scope.correctIndexData = function (data) {
var colors = ['#92278f', '#f15a29', '#006838', '#27aae1', '#262262', '#754c29', '#ee2a7b', '#8dc63f', '#fff200'];
var row = 0;
var column = 0;
var correctedData = new Array(data.length);
for (var index = 0; index < data.length; index++) {
var newIndex = scope.getCorrectedIndex(row,column,data);
if(data.length>=10){
correctedData[index] = data[newIndex];
}
else{
correctedData[newIndex] = data[index];
correctedData[newIndex].color = colors[newIndex];
}
if (column === 2) {
column = 0;
row++;
} else {
column++;
}
}
return correctedData;
};
scope.getCorrectedIndex = function (row, column, data) {
var newIndex;
var rows = Math.ceil(data.length/3.0); //number of rows in table
//handle the first row since there can be verying number of columns per row
if (row === 0) {
if(column === 0){
newIndex = 0;
}
else if (column === 1) {
newIndex = rows;
} else if(column == 2){
if(data.length % 3 == 1){
newIndex = rows * 2 -1;
}
else{
newIndex = rows * 2;
}
}
} else {
if(data.length % 3 === 0){
newIndex = (row) + (3 * column);
}
else if(data.length % 3 == 1){
if(column === 0 || data.length % 7 === 0){
newIndex = (row) + (3 * column);
}
else{
newIndex = (row) + (3 * column) + 1;
}
}
else{
if(column === 0){
newIndex = (row) + (3 * column);
}
else{
newIndex = (row) + (3 * column) + 2;
}
}
}
return newIndex;
};
因此,輸入數組的長度將始終爲7,8或9? –
它可以是任意長度。我只是以這些爲例。 – user489041
好的,謝謝你澄清。所以唯一的限制是總是3列。 –