我有一个像这样的对象数组
var card = [
{name:'square',color:'red'},
{name:'triangle',color:'black'},
{name:'circle',color:'blue'},
{name:'oval',color:'yellow'},
{name:'pentagon',color:'green'}
]
我想按照上面的形状生成水平序列的7x7网格,并显示每个的名称,因为数组只有5个对象,我想在第5个元素之后,再次从第一个对象开始,这样说
SQUARE | TRIANGLE | CIRCLE | OVAL | PENTAGON | SQUARE | TRIANGLE
CIRCLE | OVAL | PENTAGON | SQUARE | TRIANGLE | CIRCLE | OVAL
PENTAGON | SQUARE | TRIANGLE | CIRCLE | OVAL | PENTAGON | SQUARE
TRIANGLE | CIRCLE | OVAL | PENTAGON | SQUARE | TRIANGLE | CIRCLE
OVAL | PENTAGON | SQUARE | TRIANGLE | CIRCLE | OVAL | PENTAGON
SQUARE | TRIANGLE | CIRCLE | OVAL | PENTAGON | SQUARE | TRIANGLE
CIRCLE | OVAL | PENTAGON | SQUARE | TRIANGLE | CIRCLE | OVAL
答案 0 :(得分:1)
使用<table>
您可以按照以下示例进行操作。数组的偏移量计算如下:
((i * 7 ) + j) % 5
我更改了颜色以使输出更具可读性。
var card = [
{name:'square',color:'pink'},
{name:'triangle',color:'lightgrey'},
{name:'circle',color:'lightblue'},
{name:'oval',color:'yellow'},
{name:'pentagon',color:'lightgreen'}
];
var table = document.getElementById('grid');
for(var i=0; i<7; i++) {
row = grid.insertRow(-1);
for(var j=0; j<7; j++) {
cell = row.insertCell(-1);
cell.innerHTML = card[((i*7)+j) % 5].name;
cell.style.backgroundColor = card[((i*7)+j) % 5].color;
}
}
<table id="grid">
</table>
答案 1 :(得分:1)
模数或remainder operator (%
)可以解决这个问题:
var card = [
{name:'square',color:'pink'},
{name:'triangle',color:'lightgrey'},
{name:'circle',color:'lightblue'},
{name:'oval',color:'yellow'},
{name:'pentagon',color:'lightgreen'}
];
function generateTable(grid, rows, cols) {
var row;
var cells = rows * cols;
for(var i=0; i < cells; i++){
// track row length and insert new ones when necessary
// also creates the first row
if(i % cols == 0) {
row = grid.insertRow(-1);
}
// track our position in the card list
// modulo operator lets us loop through the cards repeatedly
var thisCard = card[i % card.length];
cell = row.insertCell(-1);
cell.innerHTML = thisCard.name;
cell.style.backgroundColor = thisCard.color;
}
}
generateTable(document.getElementById('grid'), 7, 7);
&#13;
<table id="grid">
</table>
&#13;