코드 는 어떤 문자열에도 전달할 수 있는 4개의 함수로 구성됩니다.
//从侧面看金字塔 function watchPyramidFromTheSide(characters) { var str = ""; for(var i=characters.length-1;i>=0;i--){ for(var j=0;j<i;j++){ str += " "; } var num = 2 * characters.length - 1 - j * 2; for(j=0;j<num;j++){ str += characters.charAt(i); } for(j=0;j<i;j++){ str += " "; } if(i>0){ str += "\n"; } } return str; } //从上方看金字塔 function watchPyramidFromAbove(characters) { var matrix = []; var str = ""; //边最长为 var sideLongest = characters.length * 2 - 1; for(var i=0;i<characters.length;i++){ var chr = characters.charAt(i); for(var j=i;j<sideLongest-i;j++){ if(!matrix[j]){ matrix[j] = new Array(sideLongest); } for(var k=i;k<sideLongest-i;k++){ matrix[j][k] = chr; } } } //组合字符串 for(i=0;i<matrix.length;i++){ str += matrix[i].join(""); if(i<matrix.length-1){ str += "\n"; } } return str; } //能看到的金字塔字符数 function countVisibleCharactersOfThePyramid(characters) { return Math.pow(characters.length * 2 - 1,2); } //金字塔总字符数 function countAllCharactersOfThePyramid(characters) { var len = characters.length; var count = 0; while(len >= 1){ count += Math.pow(2 * len - 1,2); len--; } return count; }