我的数组的第一个元素没有显示

时间:2017-11-17 19:07:24

标签: javascript html arrays while-loop

所以这是我的javascript代码。当我使用浏览器的开发人员工具一步一步地运行它时,它会从数组中获取所有元素,但它只打印最后一个4.我将如何解决这个问题?

function showDuties() {
  var numDuties = document.getElementById('pfJobs').value;
  var i = numDuties - 1
  var t = ""
  var pfDuties = ["Auditing", "Close out registers", "Clean free weights", 
      "Sign up new members", "File paperwork"]

  while (i >= 0) {
      document.getElementById('pfj').innerHTML = t;
      t += pfDuties[i] + "<br>";
      i--;  
  }
}

&#13;
&#13;
 
&#13;
<script>

window.showDuties = function() {
  var numDuties = document.getElementById('pfJobs').value;
  var i = numDuties - 1
  var t = ""
  var pfDuties = ["Auditing", "Close out registers", "Clean free weights", 
      "Sign up new members", "File paperwork"]

  while (i >= 0) {
     document.getElementById('pfj').innerHTML = t;
      t += pfDuties[i] + "<br>";
       
      i--;  
  }
}

</script>


<form>
	<input type="submit" value="Click here" onclick="showDuties(); return false;"> 
	  to see my top 
	<input type="text" id="pfJobs" />
	  job duties here.
	<p id = "pfj">
	</p>
</form>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

因为在将元素添加到t之前添加元素。你需要移动它。更好的是,不要在每次迭代时更新它,在循环完成时更新它。

while (i >= 0) {
  t += pfDuties[i] + "<br>";
  i--;  
}
document.getElementById('pfj').innerHTML = t;