首页 > 解决方案 > 如何制作一个循环打印出第一个字母,然后在新行上打印两个,等等 - javascript

问题描述

所以我是一个初学者,我有一个练习,它指导以下内容:制作一个程序,要求输入文本,然后多次打印文本。首先只有一个字母,然后是两个,依此类推。例如:用户输入“Thomas”,打印出字符串“T”、“Th”、“Tho”、“Thom”、“Thoma”、“Thomas”。

我们应该只使用javascript,这是我到目前为止的代码:

<!DOCTYPE html>
<html lang="eng">
    <head>
        <meta charset="utf-8" />
        <title>Exercise </title>


    </head>

    <body>
        <h1>Exercise </h1>

        <!-- Form for alert button that shows result -->
        <form>
            <textarea id="mytext" rows="5" cols="20">Type here</textarea>
            <input type="button" value="Print" onclick="printit()" />
        </form>

        <div id="translated" style="background-color: gray"></div>

        <script>
        //Function for getting the result and defining the 2 numbers
            function printit() 
            {
                var temptext = document.getElementById("mytext").value;
                alert(temptext.length)
                temptext = temptext.slice(0,0+1);

                document.getElementById("translated").innerHTML=temptext;

                for (var i = 0; i < temptext; i++) 
                {
                    temptext = temptext.slice(0,0+1);
                    document.getElementById("translated").innerHTML += temptext;
                }

            }
        </script>
    </body>

</html>

标签: javascript

解决方案


for(var i=0; i<data.length; i++){
  console.log(data.substr(0,i+1));
}

其中数据是来自用户的输入。你想要这样的东西吗?


推荐阅读