用嵌套循环构建三角形

时间:2017-12-07 20:11:30

标签: javascript loops

我尝试使用嵌套循环构建三角形。



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;
&#13;
&#13;

我预计每行只有一行#34;#&#34;像这样:
enter image description here

但这是我得到的结果:
enter image description here

6 个答案:

答案 0 :(得分:2)

您需要在每次嵌套迭代之前清空您的行。如果没有这个,你就有了一行,并且每次都会将新项目连接到它。您也可以保留line变量,只需使用triangle

&#13;
&#13;
var triangle = '';

for (var row = 1; row <= 7; row++) {
  for (var x = 0; x < row; x++) {
    triangle += "#";
  }
  triangle += "\n";
}

console.log(triangle);
&#13;
&#13;
&#13;

您也可以使用String#repeat

尝试此解决方案

&#13;
&#13;
var triangle = '';

for (var row = 1; row <= 7; row++) {
  triangle += '#'.repeat(row) + '\n';
}

console.log(triangle);
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您的代码执行此操作的原因是您在每次迭代时更新line并继续追加它。如果你想做嵌套循环,那么每次你在外循环中都需要重置变量行。

&#13;
&#13;
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;
&#13;
&#13;

或者你可以保留你拥有的东西并转储内部循环,每次迭代你只需要在行中添加一个字符。

&#13;
&#13;
var line, triangle;
line = triangle = "";

for (var row = 1; row <= 7; row++) {
  line += "#";
  triangle += line + "\n";
}

console.log(triangle);
&#13;
&#13;
&#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);

您的代码不正确,因为该行在每个循环中均遵循以下步骤:

  • 第1行:line以''开头,以#结束(添加#
  • 第2行:line#开头,以###结束(添加##
  • 第3行:line###开头,以######结束(添加###
  • 第4行:line######开头,以##########结束(添加####
  • 第5行:line##########开头,以###############结束(添加#####
  • 第6行:line###############开头,以#####################结束(添加######
  • 第7行: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();

工作原理:http://rextester.com/ULY85622