我有一个这样的清单:
[[A,0,1],[A,0,0],[B,0,1],[C,1,1],[C,0,1]]
我希望用html这样打印出来:
-------------
| A | 0 | 1 |
- - -----
| | | 0 |
-------------
| B | 0 | 1 |
-------------
| C | 1 | 1 |
- ---------
| | 0 | 1 |
-------------
有没有办法在javascript中执行此操作,还是有一种简单的方法在jsp中执行此操作?
答案 0 :(得分:1)
<强> 来源: 强>
var arr = [['A',0,1],['A',0,0],['B',0,1],['C',1,1],['C',0,1]];
计算每个单元格的合并深度:
var depth = arr.map(function(item){
return item.map(function(){
return 0;
});
});
var arrLength = arr.length;
for(var index=0;index<arrLength;index++){
var subArr = arr[index];
var subLength = subArr.length;
var tIndex;
var maxtIndex = arrLength;
if(index < arrLength -1) {
for(var i=0;i<subLength;i++){
tIndex = index + 1;
while(depth[index][i] != -1 && tIndex<maxtIndex){
if(subArr[i] == arr[tIndex][i]){
depth[index][i] = depth[index][i]+1;
depth[tIndex][i] = -1;
} else {
break;
}
tIndex++;
maxtIndex = tIndex;
}
if(depth[index][i] == 0){
break;
}
}
}
}
结果表:
var tableHtml = '<table>' + arr.map(function(subArr, index){
var str = '<tr>';
for(var i=0;i<subArr.length;i++){
var iDepth = depth[index][i];
if(iDepth !== -1) {
str += '<td' + (iDepth > 0?' rowspan="'
+ (iDepth + 1)+'"':'') + '>'
+subArr[i]
+ '</td>';
}
}
return str+'</tr>';
}).join(' ') + '</table>';
演示:JSFiddle
答案 1 :(得分:1)
<强>更新强> 它现在正在工作,但仍然没有你想要的
<script>
var a = [['A','0','1'],['A','0','0'],['B','0','1'],['C','1','1'],['C','0','1']]; //your array
var table = document.getElementById('your_table'); //a table to contain the res
for (i = 0; i< a.length; i++) { //loop for num of rows
var row = table.insertRow(i); //create the row and pt it in table
for (j = 0; j < 3; j++) { //loop 3 times for colums
var cell = row.insertCell(j); //create td tag
if (i == 0)
cell.innerHTML = a[i][j];
else {
if(a[i][j] != a[i-1][j]) { // if the value not equal to the one above
cell.innerHTML = a[i][j];
}
}
}
}
</script>
答案 2 :(得分:1)
在JavaScript中,您可以按照以下方式执行
var numbers = [['A','0','1'],['A','0','0'],['B','0','1'],['C','1','1'],['C','0','1']];
var rows = "";
for(var i=0; i < numbers .length; i++){
rows = rows + "<tr>"
for(var j=0; j < 3; j++){
if(i != '0' && numbers[i][j]==numbers[i-1][j]){
rows = rows + "<td>"+"-"+"</td>"
}else{
rows = rows + "<td>"+numbers[i][j]+"</td>"
}
}
rows = rows + "</tr>"
}
var table ="<table>" + rows +"</table>"
//you can append it to DIV or any element in JSP