我尝试使用嵌套循环构建三角形。
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
for (var x = 0; x < row; x++) {
line += "#";
}
triangle += line + "\n";
}
console.log(triangle);
&#13;
答案 0 :(得分:2)
您需要在每次嵌套迭代之前清空您的行。如果没有这个,你就有了一行,并且每次都会将新项目连接到它。您也可以保留line
变量,只需使用triangle
。
var triangle = '';
for (var row = 1; row <= 7; row++) {
for (var x = 0; x < row; x++) {
triangle += "#";
}
triangle += "\n";
}
console.log(triangle);
&#13;
您也可以使用String#repeat
尝试此解决方案
var triangle = '';
for (var row = 1; row <= 7; row++) {
triangle += '#'.repeat(row) + '\n';
}
console.log(triangle);
&#13;
答案 1 :(得分:2)
您的代码执行此操作的原因是您在每次迭代时更新line
并继续追加它。如果你想做嵌套循环,那么每次你在外循环中都需要重置变量行。
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
line =""
for (var x = 0; x < row; x++) {
line += "#";
}
triangle += line + "\n";
}
console.log(triangle);
&#13;
或者你可以保留你拥有的东西并转储内部循环,每次迭代你只需要在行中添加一个字符。
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
line += "#";
triangle += line + "\n";
}
console.log(triangle);
&#13;
答案 2 :(得分:2)
function triangle(num) {
for(let i = '#'; i.length < num; i+='#') {
console.log(i)
}
}
答案 3 :(得分:1)
编辑:通过添加一行修复它 - 您需要在每次迭代后重新初始化变量“line”
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
line="";
for (var x = 0; x < row; x++) {
line += "#";
}
triangle += line + "\n";
}
console.log(triangle);
答案 4 :(得分:1)
您需要在每个循环后重置line
,因为它在每个循环中都累积了所有#
:
var line, triangle;
line = triangle = "";
for (var row = 1; row <= 7; row++) {
line = "" // Add this line
for (var x = 0; x < row; x++) {
line += "#";
}
triangle += line + "\n";
}
console.log(triangle);
您的代码不正确,因为该行在每个循环中均遵循以下步骤:
line
以''开头,以#
结束(添加#
)line
以#
开头,以###
结束(添加##
)line
以###
开头,以######
结束(添加###
)line
以######
开头,以##########
结束(添加####
)line
以##########
开头,以###############
结束(添加#####
)line
以###############
开头,以#####################
结束(添加######
)line
以#####################
开头,以############################
结束(添加#######
)答案 5 :(得分:0)
尝试以下代码:
function generatePyramid() {
var totalNumberofRows = 7;
var output="";
for (var i = 1; i <= totalNumberofRows; i++) {
for (var j = 1; j <= i; j++) {
output+= "# ";
}
print(output);
output="";
}
}
generatePyramid();