简体   繁体   中英

Forming an inverted ascii triangle art using JS looping

Without nesting loops, how are you able to form such an ascii art?

####
###
##
#

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. 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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