How to display pyramid using JavaScript?

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

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

22条回答
  •  孤街浪徒
    2020-11-29 12:13

    To draw a pyramid on the console using JavaScript

    1. Make each line have an odd number of fill characters.
    2. Prepend spaces (or 'spacer characters') before each line, excluding the last.
      To do this:
      • Use repeat() to determine the number of spacer characters for each line. You do that by passing the number of lines - 1 as an argument.

    Here's my solution

    function drawPyramid(lines, fillChar, spacerChar) {
      let fillChars = '';
      let spacer = spacerChar || ' '; // Default spacer is ' '
      let spacerCount = lines;
    
      for (let i = 1; i <= lines; i++) {
          fillChars += fillChar;
    
      // Makes lines always have an odd number of fill characters
        if (i >= 2)
            fillChars = fillChar + fillChars;
    
        console.log(spacer.repeat(spacerCount - 1) + fillChars);
        spacerCount--;
      }
    }
    
    drawPyramid(4, '*');

提交回复
热议问题