这段代码是创建一个表
var table = document.createElement("table");
if ((lines > 0) && (columns> 0)) {
var tbody = document.createElement("tbody");
var tr, td;
for (var i = 0; i < lines; i++) {
tr = document.createElement("tr");
for (var j = 0; j < columns; j++) {
td = document.createElement("td");
tr.appendChild(td);
}
tbody.appendChild(tr);
}
table.appendChild(tbody);
document.body.appendChild(table);
喜欢这张图片 1
class Panel
和 function
to putAndShowEquipment
function Panel(id, line, column) {
this.id = id;
this.lines = line;
this.columns = column;
this.equipments = [];
for(var i = 0; i < lines; i++{
this.equipments[i] = [];
}
}
Panel.prototype.putAndShowEquipment = function(line, column, equipment) {
if ((line >= 0) && (line < this.lines)
&& (column >= 0) && (column < this.columns)
&& ((equipament === void 0) || (equipament instanceof Equipament))) {
this.equipaments[line][column] = equipament;
if (equipament) {
equipament.show(this.cell(line, column));
} else {
(new View()).show(this.cell(line, column));
}
}
return this;
}
我想像这张图片 2
如果我做的话,我可以做
//panel with 4 lines and 4 columns to 16 equipments
(new Panel("panel",4,4))
.putAndShowEquipment (0, 0, new Equipament())
.putAndShowEquipment (0, 1, new Equipament())
.putAndShowEquipment (1, 0, new Equipament())
.putAndShowEquipment (1, 1, new Equipament())
.putAndShowEquipment (2, 0, new Equipament())
.putAndShowEquipment (2, 1, new Equipament())
...
;
但我尝试使用 for
创建 lines
和 columns
并放置设备,我认为可能在什么时候有限制四列,换行,我都准备好了,现在只是计算题
//four lines
for (var i = 0; i < lines; i++) {
//four columns
for (var j = 0; j < columns; j++) {
//if column is four
if (j === 4) {
//change line
//this.equipaments.lenght = 16 equipments
panel.putAndShowEquipment(i + 1, j, this.equipaments[i]);
} else {
panel.putAndShowEquipment(i, j, this.equipaments[i]);
}
}
}
有什么建议吗?
最佳答案
鉴于您更新的问题,您似乎只需要将平面数组转换为矩形数组,方法是将平面数组 this.equipaments
的每个成员传递给构造函数。
如果是这种情况,并且假定 lines * columns
的数量将等于 this.equipaments.length
,那么代替 if
语句,您只需要从 i
和 j
计算索引即可。
// lines * columns === this.equipaments.length
for (var i = 0; i < lines; i++) {
for (var j = 0; j < columns; j++) {
panel.putAndShowEquipment(i + 1, j, this.equipaments[(i * columns) + j]);
}
}
因为每行的列数相等,所以我们将当前行号乘以总列数,然后加上当前列号。
关于javascript - 使用 DOM 组织表格中的元素 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37228208/