我有一个仅使用document.write方法创建表的任务。我做的。 但是困难在于用数字填充表格。 我不明白规律性!
它是示例:
1 3 3 3 3
2 1 3 3 3
2 2 1 3 3
2 2 2 1 3
2 2 2 2 1
这是我的代码:
function numbermatrix(rows, cols) {
document.write('<table>');
for (i=0; i < rows; i++) {
document.write('<tr>');
for (j=0; j < cols; j++) {
document.write('<td>' + fill() + '</td>');
}
document.write('</tr>');
}
document.write('</table>');
function fill() {
// don't know that is the algorithm
}
}
document.write (numbermatrix(5, 5));
有人能帮他把这些食材填满吗?
答案 0 :(得分:4)
这是fill
函数的逻辑
function numbermatrix(rows, cols) {
document.write('<table>');
for (i = 0; i < rows; i++) {
document.write('<tr>');
for (j = 0; j < cols; j++) {
document.write('<td>' + fill(i, j) + '</td>');
}
document.write('</tr>');
}
document.write('</table>');
function fill(i, j) {
if(i === j) return 1; // for diagonal
else if (i > j) return 2; // for values below diagonal
else return 3; // for values above diagonal
}
}
numbermatrix(5, 5);
答案 1 :(得分:2)
对于矩阵,您可以生成嵌套数组并填充索引检查。
function numbermatrix(m, n) {
return Array.from(
{ length: m },
(_, i) => Array.from(
{ length: n },
(_, j) => i === j ? 1 : i > j ? 2 : 3)
);
}
console.log(numbermatrix(5, 5).map(a => a.join(' ')));
答案 2 :(得分:1)
您还可以使用3个简单的for循环来生成数字:
function numbermatrix(rows, cols) {
document.write('<table>');
for (let i = 0; i < rows; i++) {
document.write('<tr>');
for (let k = 0; k < i; k++) { // print 2s up to i
document.write('<td>' + 2 + ' </td>');
}
document.write('<td>' + 1 + ' </td>'); // print 1
for (let k = i; k < cols-1; k++) { // print 3s up to the end
document.write('<td>' + 3 + ' </td>');
}
document.write('</tr>');
}
document.write('</table>');
}
numbermatrix(6, 6);
答案 3 :(得分:1)
这是我的。我知道我来晚了;
function numbermatrix(rows, cols) {
let table = "<table>";
for (let i = 0; i < rows; i++) {
table += "<tr>";
for (let j = 0; j < cols; j++) {
table += "<td>";
table += (i == j) ? 1 : ((i > j) ? 2 : 3)
table += "</td>";
}
table += "</tr>";
}
return table;
}
document.write(numbermatrix(5, 6));
table td{padding:1em; border:1px solid }