钻石数字形状Javascript

时间:2017-12-09 18:34:39

标签: javascript jquery html

我想用javascript创建菱形数字 基于这个模板:



function Pyramid(number) {
  document.write("<center>"); // this to align the output in center
  if (number > 0) {
    Pyramid(number - 1); //this is to move through the number of iterations
    for (j = 1; j <= number; j++) //this loop is to print the numbers in ascending order
    {
      document.write(" " + j);
    }

    for (k = number - 1; k > 0; k--) // this loop is to print the numbers in descending order
    {
      document.write(" " + k);
    }
  }
  document.write("<br>");
}
&#13;
<table>
  <tr>
    <td>Enter a number</td>
    <td><input type="text" id="no" name="number"></td>
  </tr>
  <tr>
    <td></td>
    <td><input type=submit value="submit" id="pattern" onclick="Pyramid(document.getElementById('no').value)"></td>
  </tr>
</table>
&#13;
&#13;
&#13;

上面的javascript是渲染金字塔形状的数字,我可以以某种方式将其转换为钻石形状,行仍然是从用户输入定义的? 这是所需结果的图像。

https://drive.google.com/open?id=1QsNtpsHFgY-ornrruhiAGhZWUqA9GFxi

1 个答案:

答案 0 :(得分:0)

如果你想使用像金字塔这样的递归函数来构建一个钻石,你可以使用它但是你应该使用两个独立的函数

<html>
    <head>
        <script>
        var temp2=temp*2;
function Pyramidstart(number) {
   
  document.write("<center>"); // this to align the output in center
  if (number > 0) {
    Pyramidstart(number - 1); //this is to move through the number of iterations
    for (j = 1; j <= number; j++) //this loop is to print the numbers in ascending order
    {
      document.write(" " + j);
    }

    for (k = number - 1; k > 0; k--) // this loop is to print the numbers in descending order
    {
      document.write(" " + k);
    }
    document.write("<br>");
  }
  
}
function p(x){
  
 document.write("<center>"); // this to align the output in center
  if (x < temp) {
    p(x + 1); //this is to move through the number of iterations
    for (j = 1; j <= x; j++) //this loop is to print the numbers in ascending order
    {
      document.write(" " + j);
    }

    for (k = x - 1; k > 0; k--) // this loop is to print the numbers in descending order
    {
      document.write(" " + k);
    }
    document.write("<br>");
  }
     
  
}
</script>
</head>
    <body>
        <table>
  <tr>
    <td>Enter a number</td>
    <td><input type="text" id="no" name="number"></td>
  </tr>
  <tr>
    <td></td>
    <td><input type=submit value="submit" id="pattern" onclick="temp=document.getElementById('no').value;Pyramidstart(temp);p(1);"></td>
  </tr>
</table>
    </body>
</html>