js算法练习(三)
程序员文章站
2022-06-06 14:37:33
...
输出小九九,共有四种形状,有两种方式输出方式,第一种是用空格 来实现,如果不用css的话空格的缩进不好控制;第二种是用表格实现,缩进很好控制。
(一)空格版
1.最常见的小九九
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
for (var i = 1;i <= 9;i ++) {
for (var j = 1;j <= i;j ++) {
document.write(i + "*" + j + "=" + i * j + " ");
}
document.write("<br />");
}
</script>
</body>
</html>
2.上下相反
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
for (var i = 9;i >= 1;i --) {
for (var j = 1;j <= i;j ++) {
document.write(i + "*" + j + "=" + i * j + " ");
}
document.write("<br />");
}
</script>
</body>
</html>
3.左右相反
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
for (var i = 1;i <= 9;i ++) {
for (var k = 1;k <= 9 - i;k ++) {
document.write(" ");
}
for (var j = 1;j <= i;j ++) {
document.write(i + "*" + j + "=" + i * j + " ");
}
document.write("<br />");
}
</script>
</body>
</html>
4.上下左右都相反
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
for (var i = 9;i >= 1;i --) {
for (var k = 1;k <= 9 - i;k ++) {
document.write(" ");
}
for (var j = 1;j <= i;j ++) {
document.write(i + "*" + j + "=" + i * j + " ");
}
document.write("<br />");
}
</script>
</body>
</html>
(二)表格版
看了空格版,表格版就很好理解了,就是边循环边建立了一个表格,所以直接四个全部输出:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
document.write('<table border="0" width="100%">')
for (var i = 0;i <= 9;i ++) {
document.write('<tr>')
for (var j = 1;j <=i;j ++) {
document.write('<td bgcolor="orange">' + j + '*' + i + '=' + i*j +'</td>')
}
document.write('<tr/>')
}
document.write('</table>')
</script>
<br /><br />
<script type="text/javascript">
document.write('<table border="0" width="100%">')
for (var i = 9;i >= 0;i --) {
document.write('<tr>')
for (var j = 1;j <=i;j ++) {
document.write('<td bgcolor="orange">' + j + '*' + i + '=' + i*j +'</td>')
}
document.write('<tr/>')
}
document.write('</table>')
</script>
<br /><br />
<script type="text/javascript">
document.write('<table border="0" width="100%">')
for (var i = 1;i <= 9;i ++) {
document.write('<tr>')
//输出对应数量的空td
for(var k = 1;k <= 9 - i;k ++){
document.write('<td> </td>')
}
for (var j = 1;j <= i;j ++) {
document.write('<td bgcolor="orange">' + j + '*' + i + '=' + i*j +'</td>')
}
document.write('<tr/>')
}
document.write('</table>')
</script>
<br /><br />
<script type="text/javascript">
document.write('<table border="0" width="100%">')
for (var i = 9;i >= 1;i --) {
document.write('<tr>')
//输出对应数量的空td
for(var k = 1;k <= 9 - i;k ++){
document.write('<td> </td>')
}
for (var j = 1;j <= i;j ++) {
document.write('<td bgcolor="orange">' + j + '*' + i + '=' + i*j +'</td>')
}
document.write('<tr/>')
}
document.write('</table>')
</script>
</body>
</html>
输出结果:
上一篇: Java学习小程序(7)九九乘法表
下一篇: 要你这败家娘们有什么用