<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>打印九九乘法表</title> </head> <body> <script> document.write('<table border="1" style="border-collapse:collapse">') for (var i = 1; i <= 9; i++) { document.write('<tr>') for (var j = 1; j <= i; j++) { document.write('<td>' + j + '*' + i + '=' + i * j + '</td>') } document.write('</tr>') } document.write('</table>') </script> </body> </html>
js代码(打印三角形)
<script> //正的直角三角形 for (var i = 1; i <= 9; i++) { for (var j = 1; j <= i; j++) { document.write('★ '); } document.write('<br/>'); } document.write('<br/>'); document.write('<br/>'); document.write('<br/>'); // 倒的直角三角形 // 循环的次数,for会一次执行完成 for (var i = 1; i <= 9; i++) { // 每行的个数 for (var j = i; j <= 9; j++) { document.write('★ '); } document.write('<br/>'); } </script>
数组冒泡排序
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>数组冒泡排序</title> </head> <body> <script> var arr = [2, 5, 12, 21, 54, 22, 61, 6, 1, 72, 4, 1, 3, 5, 3, 51, 4, 2, 22] // 外层循环控制比较的轮数(length-1) for (var i = 0; i < arr.length - 1; i++) { // 外层循环控制比较的次数 for (var j = 0; j < arr.length - 1 - i; j++) { // 比较大小看前一项是否大于后一项 if (arr[j] > arr[j + 1]) { // 为true交互两个的值 var temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp } } } console.log(arr) </script> </body> </html>