Skip to content
Advertisement

Question regarding JavaScript multiplication table

I am trying to build a multiplication table and display the results, but need to put the x in the top left corner, for some reason it is showing up on the bottom right, what am I doing wrong?

document.write("<table><tbody>");
var blank = "x";
var cols = 0;
var rows = 0;
// ca
for (let rows = 0; rows <= 10; rows++) {
    document.write('<tr>');
    for (let cols = 0; cols <= 10; cols++)
        document.write('<td>' + rows + ',' + cols + '</td>')
}

if (rows === 0 && cols === 0) {
    document.write('<td>' + blank + '</td>')
}

Advertisement

Answer

“What am I doing wrong?” A lot.

You should think about what you are trying to do first, before going at it.

Your html table is ill-formed, you don’t even close the <tr> tags.

for (let row = 0; row <= 10; row++) {
    document.write('<tr>');
    for (let col = 0; col <= 10; col++) {
        if (row == 0 && col == 0) {
            document.write('<td>x</td>');
        }
        else if (row == 0) {
            document.write('<td>' + col + '</td>');
        }
        else if (col == 0) {
            document.write('<td>' + row + '</td>');
        }
        else {
            document.write('<td>' + row * col + '</td>');
        }
    }
    document.write('</tr>');
}

Try it here.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement