简体   繁体   English

努力在Javascript中创建星号

[英]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: 假设用户输入了大小5,它看起来像这样:

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

My HTML looks like: 我的HTML看起来像:

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

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

In my Javascript, I have: 在我的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>";
}

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. HTML中的换行符通常显示为空格,但您希望它们显示为换行符。 The pre tag makes newlines actually appear as new lines, so wrap the output in a pre tag: pre标签使换行符实际显示为新行,因此将输出包装在pre标记中:

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

Also, you're calling createLine like this: 此外,您正在调用createLine如下所示:

var oneLine = createLine ( i <= size );

i <= size yields a boolean ( true or false ) rather than a number. i <= size产生一个布尔值( truefalse )而不是数字。 You probably mean to just pass it i : 你可能想要通过它i

var oneLine = createLine ( i );

Additionally, you're setting size like this: 此外,您正在设置这样的size

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" . 您可能希望删除第二个等于,因为它将变量size设置为字符串"size"

And finally, you've got a few variables wrong: in makeTriangle , you're looping size times, but size is undefined; 最后,你有一些错误的变量:在makeTriangle ,你是循环size时间,但是size是未定义的; you probably meant theSize . 你可能意味着theSize In createLine , you're looping i times, but i is undefined; createLine ,你循环i次,但i没有定义; you probably meant length . 你可能意味着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. 例如,在函数makeTriangle()中使用size而不是size作为参数,在for循环条件中使用i而不是createLine()函数中的length。

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/ 代码的工作解决方案可以在这个jsFiddle中找到: http//jsfiddle.net/uwe_guenther/wavDH/

And below is a copy of the fiddle: 以下是小提琴的副本:

index.html 的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 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: 您可以利用一些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/ http://jsfiddle.net/mhtKY/4/

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

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