how to Display Pyramid using Javascript?

2020-01-27 07:14发布

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

function generatePyramid() {
    var totalNumberofRows = 5;
    var arr = new Array();
    for (var i = 1; i <= totalNumberofRows; i++) {
        for (var j = 1; j <= i; j++) {

            arr.push(j);
            console.log(j);
        }
        console.log("\n");
    }
}

Required Output

18条回答
仙女界的扛把子
2楼-- · 2020-01-27 07:48

Another Option

One line of code:

function generatePyramid(n) {
    return [...Array(n)]
        .forEach((_, i) => console.log([...Array(++i)].map((_, j) => ++j).join(' ')));
}
查看更多
家丑人穷心不美
3楼-- · 2020-01-27 07:51

You can FRAME for loop conditions for any patterns given either it may be triangle, right angled triangle,inverse triangle etc.. For more info refer the below code and workbook image

//1, 3, 5,7,9.. ---> Odd number series (stars) appear in pyramid pattern //1, 2, 3,4,5.. ----> Counter (number of rows)

//For every each counter there exist 2*n-1 value

function pyramid(n) {  //Input or number of rows
for (var i = 1; i <= n; i++) {
    var s = "";
    for (var j = 1; j <= (2 * n - 1); j++) {   ////For every each counter there exist 2*n-1 value
        (j >= n + 1 - i && j <= n - 1 + i) ? s += "*" : s += " ";   //Check the work book image
    }
    console.log(s);
}

} pyramid(5);enter image description here

For your requirement , code is below

function generateNumberTriangle(v) {
for (var i = 1; i <= v; i++) {
    var chars = " ";
    for (var j = 1; j <= v; j++) {
        if (j <= i) { chars += j + "  "; }
    }
    console.log(chars);
}

} generateNumberTriangle(7);

查看更多
淡お忘
4楼-- · 2020-01-27 07:53

You should generate an array on every row iteration and output it at the end:

function generatePyramid() {
    var totalNumberofRows = 5,
        arr;
    for (var i = 1; i <= totalNumberofRows; i++) {
        arr = [];
        for (var j = 1; j <= i; j++) {
            arr.push(j);            
        }
        console.log(arr.join(" ") + "\n");
    }
}
查看更多
闹够了就滚
5楼-- · 2020-01-27 07:54

This could be done using a single for loop.

var num = "";
var size = prompt("Enter the size of the pyramid");
for(var i=1; i<=size; i++)
{
  num = num + i
  console.log(num);
}

查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-01-27 07:54

This will create a proper pyramid in a console.

function createPyramid(rows)
{
for(var i=0;i<rows;i++) {
var output="";
    for(var j=0;j<rows-i;j++) {
        output+=" ";
    }
    for(var k=0;k<=i;k++) {    
       output += "* ";
    }
    console.log(output);  
}  
}
createPyramid('5') //pass number as row of pyramid you want.
查看更多
The star\"
7楼-- · 2020-01-27 07:55

Here's a simple solution using ES6 syntax

function generatePyramid(num) {
  let number = '';

  for (let i = 1; i <= num; i++) {
    console.log(number += i);
  }
}
generatePyramid(5);
查看更多
登录 后发表回答