1. 要求:
2. 菱形思路:算出每行要打印的“*”数与空格数
第i行:“*”号数 2*i-1 空格数 num-i
function Pig() { } Pig.prototype.name = "George"; Pig.prototype.age = 6; Pig.prototype.weight = 30; Pig.prototype.color = "pink"; Pig.prototype.print = function(num) { for (var i = 1; i < num+1; i++) { var times = 2*i-1; var time = 0; while(time!= num-i){ document.write(" ");//空格需通过转义后打印,如果格式不正确,需检查此处是“ ”还是转义字符“ ” time++; } while(times!= 0){ document.write("*"); times--; } document.write("<br />"); } } var pig1 = new Pig(); pig1.print(5);
function Pig() { } Pig.prototype.name = "George"; Pig.prototype.age = 6; Pig.prototype.weight = 30; Pig.prototype.color = "pink"; Pig.prototype.print = function(num) { for (var i = 1; i < num+1; i++) { var times = 2*i-1; var time = 0; while(time!= num-i){ document.write(" "); time++; } while(times!= 0){ document.write("*"); times--; } document.write("<br />"); } for (var i = num-1; i > 0; i--) { var times = 2*i-1; var time = 0; while(time!= num-i){ document.write(" "); time++; } while(times!= 0){ document.write("*"); times--; } document.write("<br />"); } } var pig1 = new Pig(); pig1.print(5);
3. 空心金字塔
function Pig() { } Pig.prototype.name = "George"; Pig.prototype.age = 6; Pig.prototype.weight = 30; Pig.prototype.color = "pink"; Pig.prototype.print = function(num) { for (var i = 1; i < num; i++) { for (var time = 1; time < num+i; time++) { if((time == num-i+1)||(time == num+i-1)) document.write("*"); else { document.write(" "); } } document.write("<br />"); } var times = 2*num-1; while(times!=0){ document.write("*"); times--; } } var pig1 = new Pig(); pig1.print(5);
4.空心菱形
function Pig() { } Pig.prototype.name = "George"; Pig.prototype.age = 6; Pig.prototype.weight = 30; Pig.prototype.color = "pink"; Pig.prototype.print = function(num) { for (var i = 1; i < num+1; i++) { for (var time = 1; time < num+i; time++) { if((time == num-i+1)||(time == num+i-1)) document.write("*"); else { document.write(" "); } } document.write("<br />"); } for (var i = num-1; i >0; i--) { for (var time = 1; time < num+i; time++) { if((time == num-i+1)||(time == num+i-1)) document.write("*"); else { document.write(" "); } } document.write("<br />"); } } var pig1 = new Pig(); pig1.print(5);