JavaScript: Print Numbers Divisible by 6 and 9 in a Table
This JavaScript code snippet aims to print numbers divisible by both 6 and 9 in a table format. It demonstrates fundamental JavaScript concepts like loops, conditional statements, and string manipulation. Here's the corrected version of the code:
document.write('<table>');
var count = 0;
for(var shu = 1; shu <= 1000; shu++){
if(shu % 6 == 0 && shu % 9 == 0){
document.write('<td>' + shu + '</td>');
count++;
}
if(count % 7 == 0){
document.write('</tr><tr>');
}
}
document.write('</tr></table>');
Explanation:
- The
countvariable is initialized to 0 outside the loop. It keeps track of how many numbers divisible by 6 and 9 have been found. - The
forloop iterates through numbers from 1 to 1000. - Inside the loop, if a number is divisible by both 6 and 9 (using the modulo operator
%), it's added to a new table cell (<td>). - If the
countis a multiple of 7, a new table row (<tr>) is started to arrange the numbers in groups of 7. - Finally, the table is closed (
</table>).
Note: This code assumes there's an existing HTML page. If you need to create a new page with just the table, add <html>, <head>, <body> tags accordingly. This example demonstrates a simple way to generate HTML content dynamically using JavaScript. You can adapt this code to create more complex table structures or modify the conditions for number selection.
原文地址: https://www.cveoy.top/t/topic/mTrj 著作权归作者所有。请勿转载和采集!