如何在javascript中制作等腰三角形?

时间:2021-02-25 07:15:41

标签: javascript for-loop

我想尝试制作等腰三角形,但制作有困难 到目前为止,我得到了:

function pyramid(N) {
  let result = "";
  for (let i = 1; i <= N; i++) {
    for (let j = 1; j <= N; j++) {
      if (i >= j) {
        result += i + " ";
      } else {
        result += " ";
      }
    }
    result += '\n';
  }
  return result
}
console.log(pyramid(5));

我的输出:

1
2 2       
3 3 3     
4 4 4 4   
5 5 5 5 5 

我想要的输出是:

     1
    2 2
   3 3 3
  4 4 4 4
 5 5 5 5 5 

是否需要再次循环才能完成?

2 个答案:

答案 0 :(得分:1)

以下代码将为您提供所需的输出。

    function pyramid(N){
        let result = "";
        for(let i = 1 ; i <= N ; i++) {
            for(j = N ; j > i ; j--) {
              result += " ";
            }
            for(j = 1 ; j<= i ; j++) {
              result += i + " ";
            }
            result += "\n";
        }
        return result;
    }
    console.log(pyramid(5));

答案 1 :(得分:0)

您可以用您的原始代码替换 const line 的创建,这只是更简洁一点。

function pyramid(N) {
  let result = "";
  // Figure out the length of the last line.
  const lastLineLength = 2 * N - 1;
  for (let i = 1; i <= N; i++) {
    // Create an array of length i, fill it with the digit i,
    // join by spaces to create the string.
    const line = new Array(i).fill(i).join(" ");
    // Figure out how much padding to add to this line to center-align the triangle.
    const leftPaddingLength = Math.floor((lastLineLength - line.length) / 2);
    // Create the padded line.
    const paddedLine = line.padStart(line.length + leftPaddingLength);
    result += paddedLine + "\n";
  }
  return result;
}
console.log(pyramid(5));