reactjs JavaScript数字模式打印

jfgube3f  于 2023-04-29  发布在  React
关注(0)|答案(3)|浏览(124)

如何使用javascript打印下面的模式

n = 4

1
2 5
3 6 8
4 7 9 10

我尝试了下面的代码,但它打印的增量数字行

const pattern = (n) => {
  let count = 1;
  for (let row = 0; row < n; row++) {
    for (let col = 0; col <= row; col++) {
      document.write(count + " ");
      count++;
    }
    document.write("<br/>");
  }
};

pattern(4);

但预期是在列中打印递增的数字

6rqinv9w

6rqinv9w1#

你快进球门了。..试试这个:

const pattern = (n) => {
      for (let row = 1; row <= n; row++) {
        let currentNum = row;
        let printRow = "";
       
        for (let j = 1; j <= row; j++) {
          printRow += currentNum + " ";
          currentNum += (n - j) ;
        }
        console.log(printRow);
      }
    };
    
    pattern(4);

作为你的例子,而不是console.log,你可以这样做

document.write(printRow + "<br/>");
rseugnpd

rseugnpd2#

let count = 1;var a={},n=4;
  for (let row = 0; row < n; row++) {
    for (let col = row+1; col <=n; col++) {
        if(!a[col]){
            a[col]='';
        }
      a[col]+= count + ' ';
      count++;
    }
    console.log(a[row+1]);
  }
brc7rcf0

brc7rcf03#

let arr = [];
  let val = 1;

  for (let i = 0; i < n; i++) {
    arr[i] = [];
    for (let j = 0; j < n - i; j++) {
      arr[i][j] = val;
      val++;
    }
  }

  let output = "";

  for (let i = 0; i < n; i++) {
    for (let j = 0; j <= i; j++) {
      output += arr[j][i - j] + " ";
    }
    output += "\n";
  }

  console.log(output);
}

printIncrementalColumn(5);

相关问题