javascript - 如何在 Javascript 中的字符串末尾添加一个空格

标签 javascript html string

我正在编写一个程序,它根据用户输入创建一个倾斜的 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 = '&nbsp;'; 

关于javascript - 如何在 Javascript 中的字符串末尾添加一个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42599063/

相关文章:

php - 将平面数组转换为要保存在数据库中的分隔字符串

javascript - 从 Alloy UI 数据表创建 JSON

javascript - 使用Python和Flask实时更新心电图

javascript - 当我尝试保存提交表单中的值时,本地存储给出未定义的结果

javascript - Angularjs 中函数的参数神奇地匹配?

html - 如何将图像与其他元素放在列表中居中

JavaScript 全局 boolean 变量将自身转换为字符串

python - 使用 Python 从字符串中删除度数符号

javascript - jQuery Lite 内容 slider - 将类添加到当前幻灯片

javascript - HTTP 请求错误与响应错误