使用javascript函数打印三角形

时间:2018-02-22 14:34:50

标签: javascript



function makeLine(length) {
  var line = "";
  for (var i = 1; i <= length; i++) {
    for (var j = 1; j <= i; j++) {
      line += "*";

    }

  }
  return line + "\n";
}
console.log(makeLine(2));
&#13;
&#13;
&#13;

我正在尝试打印三角形,我不知道我在哪里做错了,有些人可以解释使用嵌套循环打印三角形背后的逻辑

*
**
***

6 个答案:

答案 0 :(得分:2)

完成一行打印后,您需要添加换行符&#34; \ n&#34;这样你就可以移动到下一行了。你可以这样做:

&#13;
&#13;
function makeLine(length) {
  // length has the number of lines the triangle should have
  var line = "";
  for (var i = 1; i <= length; i++) {
    // Enter the first for loop for the number of lines
    for(var j=1; j<=i; j++){ 
      // Enter the second loop to figure how many *'s to print based on the current line number in i. So the 1st line will have 1 *, the second line will have 2 *s and so on.
      line += "*";
    }
    // Add a newline after finishing printing the line and move to the next line in the outer for loop
    line+="\n";

  }
  // Print an additional newline "\n" if desired.
  return line + "\n";
}
console.log(makeLine(2));
&#13;
&#13;
&#13;

答案 1 :(得分:1)

\n处于不正确的位置。

function makeLine(length) {
  var line = "";
  for (var i = 1; i <= length; i++) {
    for (var j = 1; j <= i; j++) {
      line += "*";

    }
    line += "\n";
  }
  return line;
}
console.log(makeLine(5));

答案 2 :(得分:1)

不要忘记.repeat()

function makeLine(length) {
  var line = "";
  for (var i = 1; i <= length; i++) {
    line+="*".repeat(i)+"\n";
  }
  return line;
}
console.log(makeLine(3));

答案 3 :(得分:1)

function makeLine(length) {
 var line = "";
 for (var i = 1; i <= length; i++) {
   for (var j = 1; j <= i; j++) {
       line += "*";
   }
   // add new line after loop is completed
   line = line + "\n"
}
return line + "\n";

} 的console.log(makeLine(5));`

当内循环完成时,您需要将\n添加到行

答案 4 :(得分:1)

function hashTriangle(length)
{
let str="";
for(let i=0;i<length;i++) 
    {

    str+="#";
    console.log(str);
    }
}
hashTriangle(7);

console.log()打印新行。因此,不必将嵌套循环和混乱的换行符附加到我们的字符串中。

答案 5 :(得分:0)

使用padStartpadEndrepeat方法打印左右三角形的简单解决方案

左三角形

const printLeftTriangle = (n) => {
  let output='';
  for (let i = 1; i <= n; i++) {
   output +="*".repeat(i).padStart(n) + "\n";
  }   
  return output;
}

console.log(printLeftTriangle(5));

直角三角形

const printRightTriangle = (n) => {
 let output='';
 for (let i = 1; i <= n; i++) {
  output +="*".repeat(i).padEnd(n) + "\n";
 }   
 return output;
}

console.log(printRightTriangle(5));