我的数组包含一个空白 space [" "]。当我用下划线加入 space 时,结果字符串中的 space 元素在 html 中不可见

My array contains a blank space [" "]. When I .join the space with underscores, the space element in the resulting string is not visible in the html

在控制台显示时,我在p标签之间得到的结果包含索引3中的space,这是正确的。

但是在页面上显示时我得到“_ _ _ _”。索引 3 中的 space 不可见。这是 CodePen

如何让下划线之间的space显示在页面上?我什至不能在这里显示 SPACE!它显示为“_ _ _ _”。下划线2和3之间应该有一个space!

非常感谢!

.toString 而不是 .join 没有区别。

.textContent 而不是 .innerHTML 也没有区别。

<html>
  <p id="myid"></p>

  <script>
    var myArray = ["_", "_", " ", "_", "_"];
    var hiddenWord = document.getElementById('myid');
    var temp;

    function newGame() {
      temp = myArray.join(" ");
      hiddenWord.innerHTML = temp;
    }

    newGame();
    console.log("temp variable", temp);
    console.log(myArray);
  </script>
</html>

渲染 HTML 时,通常白色序列 space 会折叠成单个白色 space。在元素上使用 white-space: pre; 以保留白色序列 spaces:

var myArray = ["_", "_", " ", "_", "_"];
var hiddenWord = document.getElementById('myid');
var temp;

function newGame() {
  temp = myArray.join(" ");
  hiddenWord.innerHTML = temp;
}

newGame();
#myid {
  white-space: pre;
}
<p id="myid"></p>

许多 space 在 HTML 中呈现为单个 space,与所有其他白色 space 一样。为了克服这个问题,你可以使用不间断的 space &nbsp;,它给出了想要的 space.

function newGame() {
    temp = myArray.join(" ").replace(/\s/g, '&nbsp;');
    hiddenWord.innerHTML = temp;
 }

var myArray = ["_", "_"," ","_","_"],
    hiddenWord = document.getElementById('myid'),
    temp;

newGame();
console.log("temp variable", temp);
console.log(myArray);
<p id="myid"></p>

发生这种情况是因为 html 没有考虑两个空格,您可以将其视为 javascript

中的修剪字符串

不使用 space(' ') 加入,而是使用 html

的 nbsp
temp = myArray.join("&nbsp;");