0

i have tried the code below, but it just show an inverted pyramid with no hollow. it also has an error unknown

var row = 5
for (i = 1; i <= row; i++) {
  for (j = 1; j < i; j++) {
    document.write("&nbsp;");
  } {
    for (j = 1; j <= (row * 2 - (2 * i - 1)); j++) {
      if (i == 1 || j == 1 || j == (row * 2 - (2 * i - 1))) {
        document.write("*");
      } else {
        document.write("&nbsp;");
      }
    }
  }
  document.write("<br/>")
}

i expected a hollow inverted star pattern

Rajesh
  • 24,354
  • 5
  • 48
  • 79
afif julio
  • 27
  • 6
  • *it also has an error* Can you share what the error message is? – Rajesh Sep 12 '19 at 10:15
  • Not getting into logic, every character has its own width. So a space and a asterisk will not occupy same space. Try adding following style: `body { font-family: monospace }` – Rajesh Sep 12 '19 at 10:29

2 Answers2

0

This will help. if you think the shape is not correct.

var row = 5
for (i = 1; i <= row; i++) {
  for (j = 1; j < i; j++) {
    document.write("&nbsp;&nbsp;");
  } {
    for (j = 1; j <= (row * 2 - (2 * i - 1)); j++) {
      if (i == 1 || j == 1 || j == (row * 2 - (2 * i - 1))) {
        document.write("*");
      } else {
        document.write("&nbsp;&nbsp;");
      }
    }
  }
  document.write("<br/>")
}
Sundeep Pidugu
  • 2,377
  • 2
  • 21
  • 43
0

I think you should change document.write() because document.write shows error like document.write can be a form of eval and it is bad practice as mentioned in link document.write

HTML can be :

<div id="divid">
</div>

You can write javascript code as follows:

var theDiv = document.getElementById("divid");
var content = document.createTextNode('\u00A0');
theDiv.appendChild(content);
var content = "";
var row = 5
for (i = 1; i <= row; i++) {
  for (j = 1; j < i; j++) {
   var content = document.createTextNode('\u00A0\u00A0');
   theDiv.appendChild(content);
  } 
    for (j = 1; j <= (row * 2 - (2 * i - 1)); j++) {
      if (i == 1 || j == 1 || j == (row * 2 - (2*i - 1))) {
         var content = document.createTextNode("*");
         theDiv.appendChild(content);
      } else {
        var content = document.createTextNode('\u00A0\u00A0');
        theDiv.appendChild(content);
      }
    }

     var content = document.createElement("br");
     theDiv.appendChild(content);
  }

Here is the link of jsfiddle: jsfiddle

Ishpreet
  • 659
  • 5
  • 19