我正在编写一个程序,它根据用户输入创建一个倾斜的 d。 该程序询问行数并相应地产生输出。 如果用户输入 5,它应该产生以下输出:
d
d
d
d
我的实际输出是:
d
d
d
d
这是我的 Javascript 代码:
spaceArray = [];
space = ' ';
spaceMain = ' ';
function processingFunction(rows){ //passes the input as variable rows
var spaceCounter = 0;
var counter = 0;
while (counter<rows){
while (spaceCounter<counter){
spaceMain = spaceMain + space; //adds a space before the d
spaceCounter++;
}
counter++;
spaceCounter=0;
spaceArray.push(spaceMain); //adds spaceMain to the end of spaceArray
spaceMain = ' ';
}
for (i = 0; i<rows; i++){
d = spaceArray[i]+"d<br>";
document.getElementById("outputNumber1").innerHTML += d;
}
}
当我将空间变量字符串从 ' ' 替换为 '-' 时,它的输出似乎是:
d
-d
--d
---d
我不确定我需要更改什么才能获得上述输出,但使用空格而不是破折号。
HTML:
<!DOCTYPE>
<html>
<head>
</head>
<style>
body{background-color: green;}
</style>
<body>
<center><h2>Slanted d</h2></center>
<h3>Input the number of rows you would like your slanted d to be in the input text box</h3>
<input type="text" id="inputNumber"></input>
<button type="button" onclick="processingFunction(document.getElementById('inputNumber').value)">Create slanted d</button>
<br><br>
<output type="text" id="outputNumber1"></output>
<script src="slantedDJS.js"></script>
</body>
</html>
最佳答案
使用 html 代码
代替空格,您的代码将开始工作,因为默认情况下浏览器只接受一个空格,无论您输入多少个空格。
示例:
space = ' ';
关于javascript - 如何在 Javascript 中的字符串末尾添加一个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42599063/