打印三角形图案的更短方式 JavaScript

Shorter Way of Prinitng Triangle Patterns JavaScript

我正在尝试寻找一种更短的方法来打印直角三角形和等腰三角形,而无需使用那么多嵌套循环。请帮忙,到目前为止,这是我的代码,它可以工作我只是找不到更短的编写方式:

//right-triangle
let triangleStr = "";
let num = 5;
for (let i = 1; i <= num; i++) {
  for (let j = 0; j < num - i; j++) {
    triangleStr += " ";
  }
  for (let k = 0; k < i; k++) {
    triangleStr += "*";
  }
  triangleStr += "\n";
}
console.log(triangleStr);

//isosceles-triangle
triangleString = "";
for (let i = 1; i <= num; i++) {
  for (let j = 1; j <= num - i; j++) {
    triangleString += " ";
  }
  for (let k = 1; k <= 2 * i - 1; k++) {
    triangleString += "*";
  }
  triangleString += "\n";
}
console.log(triangleString);

如果你只想使用一个循环,你可以使用ECMAScript6或更高版本的repeat()方法。

对于直角三角形:

const line = 5;
let rightTriangle = "";
for (let l = 1; l <= line ; l++) {
    const indent = line-l;
    rightTriangle += `${" ".repeat(indent)}${"*".repeat(l)}${"\n"}`;
}
console.log(rightTriangle);

对于等腰三角形:

const line = 5;
let isoscelesTriangle = "";
for (let l = 1; l <= line ; l++) {
    const indent = line - l;
    isoscelesTriangle += `${" ".repeat(indent)}${"*".repeat(2*l-1)}${"\n"}`;
}
console.log(isoscelesTriangle);