簡體   English   中英

努力在Javascript中創建星號

[英]struggling with creating asterisks in Javascript

我一直在努力解決這個問題。 我想要創建的是根據用戶的輸入輸出一個三角形的星號。 假設用戶輸入了大小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>";
}

誰有任何關於我如何去做的小費? 非常感謝!

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

盡管如此, 它仍然有效

您的代碼中存在多個錯誤。 例如,在函數makeTriangle()中使用size而不是size作為參數,在for循環條件中使用i而不是createLine()函數中的length。

另一個是:

采用

return aLine + "<br/>";

代替

return aLine + "\n";

代碼的工作解決方案可以在這個jsFiddle中找到: http//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);

您可以利用一些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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM