【问题标题】:Writing text expanding (pyramid) [closed]书写文本扩展(金字塔)[关闭]
【发布时间】:2018-03-08 08:29:01
【问题描述】:

对不起,我的英语不好。

我需要一个使用循环来打印这种输出的代码:

*
**
***
****
*****
******
*******
********
*********
**********

这就像从 1 数到 10,但它不是数字,而是 * 显示值。

我做了很多研究,但找不到合适的方法来创建一个循环,从我想要的任何数字开始计数并让它看起来像那个输入。

【问题讨论】:

标签: javascript html


【解决方案1】:

您要完成的工作相当简单。您只需要一个for 循环即可:

  1. 按照指定的次数进行迭代,
  2. 使用String.prototype.repeat 创建与行号一样多的星号&
  3. 在字符串末尾添加换行符"\n"

示例:

/* The function that creates the desired output for as many rows as given. */
function createOutput(rows) {
  /* Create an empty string. */
  var str = "";
  
  /* Loop [rows] times and add [i] asterisks & a newline to the string each loop. */
  for (var i = 1; i <= rows; str += "*".repeat(i) + "\n", i++);
  
  /* Return the string. */
  return str;
}

/* Create an output of 5 rows and log it in the console. */
console.log(createOutput(5));

注意事项:

  1. 由于 String.prototype.repeat 是在 EcmaScript 6 中添加的,它可能并不适用于所有人。如果你遇到这个问题,你可以用Array(i+1).join("*")代替"*".repeat(i)

  2. 为了在您的应用程序中包含上述代码,您必须:

    • 将其保存在文件中并使用以下命令加载:
      &lt;script src = "file.js" type = "application/javascript"&gt;&lt;/script&gt;

    • 或将其粘贴到您的 HTML 文件中:
      &lt;script type = "application/javascript"&gt;[the code]&lt;/script&gt;

【讨论】:

    【解决方案2】:

    在 Javascript 中,您可以简单地使用一个 for 循环和 repeat 函数:

    function pyramid(max, c) {
        r = "";
        for(i=1; i<=max; i++) {
            r = r + c.repeat(i) + "\n";
        }
        return r;
    }
    
    console.log(pyramid(10, '*'));

    使用:金字塔(length, char);

    var my result = pyramid(10, '*');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-17
      • 1970-01-01
      相关资源
      最近更新 更多