简体   繁体   English

使用JS循环形成倒置的ascii三角图

[英]Forming an inverted ascii triangle art using JS looping

Without nesting loops, how are you able to form such an ascii art? 没有嵌套循环,您如何形成这样的ascii艺术?

####
###
##
#

This is what I currently have: 这是我目前拥有的:

function invertTriangle (row) {
  var asteric = "*" * row;
  for ( var y=row; y>=row; y--){
      asteric = asteric - "*";
      console.log(asteric);
  }
};

invertTriangle(10);

I will appreciate your help and explanation! 感谢您的帮助和解释!

Thank you! 谢谢!

Try: 尝试:

 var string = ""; for (var i = 0, j = 4, k = 4; i < 10; i++) { string += "*"; if (--j === 0) { j = --k; string += "\\n"; } } alert(string); 

Hope that helps. 希望能有所帮助。

Here's a way of doing it with recursion. 这是使用递归的一种方法。

Basically, you call the function with the number of chars you'd like printed on the first line. 基本上,您以第一行中要打印的字符数调用该函数。 It then constructs a string with this many characters in it. 然后,它构造一个包含这么多字符的字符串。 It then decrements the number of chars wanted and, if this number is greater than 0, calls itself again and adds the new result to the current result. 然后,它减少所需的字符数,如果该字符数大于0,则再次调用自身并将新结果添加到当前结果中。 This continues until we get to a line that requires zero characters. 这一直持续到我们到达需要零个字符的行为止。 At this point, the function no longer calls itself and the fully constructed string is returned to the original caller. 此时,该函数不再调用自身,并且将完全构造的字符串返回给原始调用者。

Code: 码:

<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}

window.addEventListener('load', onDocLoaded, false);

function onDocLoaded()
{
    byId('triTgt').innerText = makeTriString(40);
}

function makeTriString(nStars)
{
    var str = '';
    for (var i=0; i<nStars; i++)
        str += "*";
    str += "\n";
    nStars--;
    if (nStars > 0)
        str += makeTriString(nStars);
    return str;
}
</script>
<style>
</style>
</head>
<body>
    <div id='triTgt'></div>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM