How to display pyramid using JavaScript?

前端 未结 22 833
长情又很酷
长情又很酷 2020-11-29 11:45

Here is the code to display pyramid but its not exactly producing required output.

相关标签:
22条回答
  • 2020-11-29 12:27

    This will create a proper pyramid in a console:

    function createPyramid(rows)
    {
        for (let i = 0; i < rows; i++) {
            var output = '';
            for (let j =0; j < rows - i; j++) output += ' ';
            for (let k = 0; k <= i; k++) output += '* ';
            console.log(output);  
        } 
    }
    
    createPyramid(5) // pass number as row of pyramid you want.

    0 讨论(0)
  • 2020-11-29 12:27

    Another Option

    One line of code:

    function generatePyramid(n) {
        return [...Array(n)]
            .forEach((_, i) => console.log([...Array(++i)].map((_, j) => ++j).join(' ')));
    }
    
    0 讨论(0)
  • 2020-11-29 12:30

    Try the below code

    function generatePyramid() {
        var totalNumberofRows = 5;
        var output = '';
        for (var i = 1; i <= totalNumberofRows; i++) {
            for (var j = 1; j <= i; j++) {
                output += j + '  ';
            }
            console.log(output);
            output = '';
        }
    }
    
    generatePyramid();
       

    0 讨论(0)
  • 2020-11-29 12:30

    I would stick to recursive approach in such a case:

    function generatePyramid (n, row = 0, line = '', number = 1) {
      
        if(row === n){
          return;
        }
        
        if (line.length === n) {
            console.log(line )
            return generatePyramid (n, row + 1)
        } 
        
        if (line.length <= row) {
            line += number;
        } else {
            line += ' ';
        }
        
        generatePyramid (n, row, line, number + 1)
      }

    0 讨论(0)
提交回复
热议问题