努力在Javascript中创建星号

时间:2013-03-03 21:06:54

标签: javascript function

我一直在努力解决这个问题。我想要创建的是根据用户的输入输出一个三角形的星号。假设用户输入了大小5,它看起来像这样:

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

我的HTML看起来像:

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

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

在我的Javascript中,我有:

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>";
}

任何人都有关于我如何做到这一点的任何提示?非常感谢你!

3 个答案:

答案 0 :(得分:1)

HTML中的换行符通常显示为空格,但您希望它们显示为换行符。 pre标记使换行实际显示为新行,因此请将输出包装在pre标记中:

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

此外,您正在调用createLine,如下所示:

var oneLine = createLine ( i <= size );

i <= size产生一个布尔值(truefalse)而不是数字。你可能只想传递它i

var oneLine = createLine ( i );

此外,您正在设置size,如下所示:

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

您可能希望删除第二个等号,因为它会将变量size设置为字符串"size"

最后,你有一些错误:在makeTriangle中,你循环size次,但size未定义;你可能意味着theSize。在createLine中,您循环i次,但i未定义;你可能意味着length

尽管如此,it works

答案 1 :(得分:1)

您的代码中存在多个错误。例如,在函数makeTriangle()中使用size而不是size作为参数,在for循环条件中使用i而不是createLine()函数中的length。

另一个是:

使用

return aLine + "<br/>";

而不是

return aLine + "\n";

您可以在此jsFiddlehttp://jsfiddle.net/uwe_guenther/wavDH/

中找到代码的工作解决方案

以下是小提琴的副本:

的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);

答案 2 :(得分:0)

您可以利用一些JavaScript技巧使代码更简洁:

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