使用构建三角形的函数。如何在不以新行结束三角形的情况下实现新行?

Using a function that builds a triangle. How to implement new line without ending triangle with a new line?

使用函数构建三角形。一个创建一组楼梯,下一个创建用于构建三角形的空间,最后一个函数将它们放在一起构建三角形。如果不在末尾 return 换行,就无法弄清楚如何构建它。

尝试将三角形函数中的高度设置为 height - 1 然后 returning stairLine(包括新行)我会 return stairLine += spaceLine(height - i , numberOfCharacters ).这不起作用,因为 i 和 numberofCharacters 没有在我的 for 循环之外定义,但我想知道我是否可以使用类似的东西。

// line function :
function line(size){
   let hashLine = '';
   for (let i = 0; i < size; i++) {
       hashLine += "#";
  }
  return hashLine;
}
//console.log(line(5));

// stairs function :
function stairs(height){
  let stairLine = '';
  let newLine = "\n";
  for (let i = 0; i <= height; i++){
    stairLine += line(i) + newLine;
  } return stairLine
}
//console.log(stairs(5));

// spaceLine function :
function spaceLine(numSpaces, numChars){
  let myLine = '';
  let lineLength = numSpaces + numChars;
  for(i = 0; i < numSpaces  ; i++){
    myLine += " ";
  }
  myLine += line(numChars);
  for(i = 0; i < numSpaces  ; i++){
    myLine += " ";
  }
  return myLine;
}
//console.log(spaceLine(3,5));


// triangle function :
function triangle(height){
  let stairLine = '';
  let newLine = "\n";
  for (let i = 0; i < height; i++){
    let numberOfCharacters = 2*i+1;
    stairLine += spaceLine(height - i , numberOfCharacters) + newLine;
  }
    return stairLine;
}

console.log(triangle(5));

我希望输出是

    #
   ###
  #####
 #######
#########

但我得到了

    #
   ###
  #####
 #######
#########
(new line here)

如果是最后一次迭代,您可以在循环中添加一个检查以省略换行符:

for (let i = 0; i < height; i++){
  let numberOfCharacters = 2*i+1;
  stairLine += spaceLine(height - i , numberOfCharacters);
  if (i !== height - 1) stairLine += newLine;
}