javascript - 如何制作一个循环打印出第一个字母,然后在新行上打印两个,等等 - 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>
解决方案
for(var i=0; i<data.length; i++){
console.log(data.substr(0,i+1));
}
其中数据是来自用户的输入。你想要这样的东西吗?
推荐阅读
- java - 在 Antlr 4 中重复评估同一访客
- python - Scikit-learn LinearRegression:如何解决错误“fit()缺少1个必需的位置参数:'y'”?
- java - Java Spark - 在使用条件时对 Spark 数据框列进行多值检查
- julia - 如何在 julia Genie 应用程序中设置 cors 标头以允许来自不同域的 POST 请求
- javascript - done() 函数的含义
- php - 在 PHP 中将 SVG 加载为内联的最佳方法 - cURL 或 file_get_contents
- c# - 使用c#在windows中获取设备ID
- python - 使用 Pymongo / MongoDB 迭代游标对象的有效方法
- java - 无法加载 groovy 类
- c# - Xamarin 从 imageButton 保存图像