简体   繁体   中英

struggling with creating asterisks in Javascript

I've been struggling with this for some time now. What I wanted to create is to output a triangle of asterisks based on user's input. Let say user entered size 5, it would look something like this:

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

My HTML looks like:

<p>
Size: <input type="text" id="size">
<input type="button" value="Draw" onclick="draw()">
</p>

<pre id="output">
</pre>

In my Javascript, I have:

function draw()
{
  var size = customJS.get ( "size" ); //I have a custom library where it get the Id from HTML
  var theTriangle = makeTriangle( size.value ); //sending in the size
  customJS.set ("output", theTriangle); //will set theTriangle to display to "output" in HTML
}

function makeTriangle( theSize )
{
    var allLines = "";    // an empty string to hold the entire triangle
    for ( var i = 0; i <= size; i++) // this loop size times
    {
        var oneLine = createLine ( i <= size ); // amount of asterisks for this line
        allLines += oneLine;
    }
    return allLines;
}

function createLine ( length )
{
    var aLine = "";     // an empty string to hold the contents of this one line
    for ( var j = 0; j <= i; j++ ) //this loop length times
    {
        aLine += '*';  
    }
    return aLine + "<br>";
}

anyone have any tip on how I go about this? thank you so much!

Newlines in HTML normally display as spaces, but you want them to show as newlines. The pre tag makes newlines actually appear as new lines, so wrap the output in a pre tag:

customJS.set ("output", "<pre>" + theTriangle + "</pre>");

Also, you're calling createLine like this:

var oneLine = createLine ( i <= size );

i <= size yields a boolean ( true or false ) rather than a number. You probably mean to just pass it i :

var oneLine = createLine ( i );

Additionally, you're setting size like this:

var size = customJS.get = ( "size" );

You probably want to drop the second equals, since as is, it sets the variable size to the string "size" .

And finally, you've got a few variables wrong: in makeTriangle , you're looping size times, but size is undefined; you probably meant theSize . In createLine , you're looping i times, but i is undefined; you probably meant length .

With all that, it works .

There were several bugs in your code. For example using theSize instead size as parameter in the function makeTriangle(), using i instead of length in the createLine() function in the for loop condition.

Another one was:

use

return aLine + "<br/>";

instead of

return aLine + "\n";

The working solution for your code can be found in this jsFiddle : http://jsfiddle.net/uwe_guenther/wavDH/

And below is a copy of the fiddle:

index.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <p>Size:
         <input type="text" id="sizeTextField">
         <input id='drawButton' type="button" value="Draw">
         <div id='output'></div>
    </p>

    <script src='main.js'></script>
</body>
</html>

main.js

(function (document) {
    var drawButton = document.getElementById('drawButton'),
        sizeTextField = document.getElementById('sizeTextField'),
        output = document.getElementById('output');

    function makeTriangle(size) {
        var allLines = '';
        for (var i = 0; i <= size; i++) {
            var oneLine = createLine(i); // amount of asterisks for this line
            allLines += oneLine;
        }
        return allLines;
    }

    function createLine(length) {
        var aLine = '';
        for (var j = 0; j <= length; j++) {
            aLine += '*';
        }
        return aLine + "<br/>";
    }

    drawButton.onclick = function () {
        output.innerHTML = makeTriangle(sizeTextField.value);
    };
})(document);

You can leverage some JavaScript tricks to make the code a bit more terse:

<div style="text-align: center">
    <label>Size:
        <input type="text" id="size" value="5">
    </label> <pre id='output'></pre>

</div>
<script>
    var size = document.getElementById('size'),
        output = document.getElementById('output');

    function update() {
        var width = +size.value, // Coerce to integer.
            upsideDown = width < 0, // Check if negative.
            width = Math.abs(width), // Ensure positive.
            treeArray = Array(width).join('0').split('0') // Create an array of 0s "width" long.
                .map(function(zero, level) { // Visit each one, giving us the chance to change it.
                    return Array(2 + level).join('*'); // Create a string of *s.
                });
        upsideDown && treeArray.reverse(); // If width was negative, stand the tree on its head.
        output.innerHTML = treeArray.join('\n'); // Join it all together, and output it!
    }

    size.onkeyup = update;
    update();
    size.focus();
</script>

http://jsfiddle.net/mhtKY/4/

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