Javascript 数组和innerHTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26316536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 05:48:03  来源:igfitidea点击:

Javascript array and innerHTML

javascriptarraysinnerhtml

提问by Spoofy

I'm just started with JavaScript and I have a little problem.

我刚开始使用 JavaScript,我有一个小问题。

How do I use the innerHTMLpropriety to change the text in this element:

我如何使用innerHTML属性来更改此元素中的文本:

(function showArray(){
  var names = new Array("Bob ","Alice ","Ceaser ","David");
  names.sort();

  for (var i = 0; i < names.length; i++) {
    document.getElementById("loop").innerHTML = names[i];
    // I'm only getting "David" as output!!
  }
})();
<p id="loop">David Alice Bob Ceaser</p>

回答by Dave Chen

Try this, you just need to join the names too.

试试这个,你只需要加入名字。

function showArray() {
  var names = new Array("Bob ", "Alice ", "Ceaser ", "David");
  names.sort();

  document.getElementById("loop").innerHTML = names.join(" ");
}

showArray();
<p id="loop">David Alice Bob Ceaser</p>

回答by KooiInc

Just for the record: your code can be reduced to

仅供记录:您的代码可以简化为

 (function() {
   document.querySelector("#loop").innerHTML = 
       ["Bob ", "Alice ", "Ceaser ", "David"].sort().join(" ");
 }())
<p id="loop"></p>

回答by Oriol

In this case, better use Array.prototype.joinas suggested in @DaveChen's answer.

在这种情况下,最好Array.prototype.join按照@DaveChen 的回答中的建议使用。

However, you can't always use that. For those cases:

但是,您不能总是使用它。对于这些情况:

  • DOM operations are slow. Therefore,
    • Don't use getElementByIdinside a loop. Instead, store the element in a variable before the loop.
    • Don't modify innerHTMLat each iteration. Instead, update a string variable and only modify innerHTMLafter the loop.
  • Creating arrays using []is faster than with Arrayconstructor, and it's shorter.
  • DOM 操作很慢。所以,
    • 不要getElementById在循环内使用。相反,在循环之前将元素存储在变量中。
    • 不要innerHTML在每次迭代时修改。相反,更新字符串变量并仅innerHTML在循环后修改。
  • 使用创建数组[]比使用Array构造函数更快,而且时间更短。

However, note that using innerHTMLmay produce html injection. If you just want to add text, better use textContentinstead.

但是,请注意,使用innerHTML可能会产生 html 注入。如果您只想添加文本,最好textContent改用。

(function showArray(){
  var names = ["Bob ","Alice ","Ceaser ","David"],
      el = document.getElementById("loop"),
      html = '';
  names.sort();
  for (var i = 0; i < names.length; i++) html += names[i];
  el.textContent = html;
})();
<p id="loop">David Alice Bob Ceaser</p>