To create a multiplication table in JavaScript, you can use a nested loop to iterate over the rows and columns of the table, and calculate the products of the corresponding values.
Here’s an example of how you could create a multiplication table for the numbers 1 through 10:
let table = '';
for (let i = 1; i <= 10; i++) {
for (let j = 1; j <= 10; j++) {
table += (i * j) + '\t';
}
table += '\n';
}
console.log(table);
In this example, the outer loop iterates over the rows of the table (from 1 to 10), and the inner loop iterates over the columns (also from 1 to 10). The product of the corresponding values is calculated using i * j
, and the result is concatenated to the table
variable using the +=
operator. Finally, a newline character (\n
) is added after each row to create the desired format for the table.
You can also use JavaScript to generate an HTML table, and display it on a web page, by constructing HTML elements and appending them to the document
. Here’s an example:
let table = document.createElement('table');
for (let i = 1; i <= 10; i++) {
let row = document.createElement('tr');
for (let j = 1; j <= 10; j++) {
let cell = document.createElement('td');
cell.innerHTML = i * j;
row.appendChild(cell);
}
table.appendChild(row);
}
document.body.appendChild(table);
In this example, the outer loop creates a tr
element for each row, and the inner loop creates a td
element for each cell. The products are stored in the innerHTML
property of each cell, and the cells are appended to the row using the appendChild()
method. Finally, the table is appended to the body
element of the document using appendChild()
.
+ There are no comments
Add yours