JavaScript 之for循环打印金字塔图形

需求:1、用for循环打印半个金字塔图形

n=5:

<html>
<head>
<title>打印半个金字塔</title>
<script type="text/javascript">
var n = window.prompt("请输入金字塔的高度(行数)");
	for(var i=0;i<=n;i++){
	for(var j=0;j<i;j++){
	    document.write("*");
	}
	document.write("<br>");
	}
</script>
</head>
<body>
</body>
</html>

需求:2、用for循环打印整个金字塔

n=5:

<html>
<head>
<title>打印整个金字塔</title>
<script type="text/javascript">
var n = window.prompt("请输入金字塔的高度(行数)");
	for(var i=1;i<=n;i++){
        //打印空格  n-i 总层数-第几层
	for(var j=1;j<=(n-i);j++){
	    document.write("&nbsp");
	}
	//打印*  2*(i-1)+1  2*(第几层-1)+1
	for(var k=1;k<=(2*i-1);k++){
		document.write("*");
	}
	//换行
	document.write("<br>");
}
</script>
</head>
<body>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/sunny123x/article/details/79829839