for循环不执行数组中的最后一个函数(JavaScript)

时间:2017-01-03 02:40:50

标签: javascript arrays

未执行boxFill()数组中的最后一个函数。我已经尝试计算阵列的长度,但没有运气。 (我对js很新,只是说)。它迭代前四个索引,并且总是不执行最后一个索引,即使我改变了索引的位置。

var pResult1 = document.getElementById("result1");
 var pResult2 = document.getElementById("result2");
 var pResult3 = document.getElementById("result3");
 var pResult4 = document.getElementById("result4");
 var pResult5 = document.getElementById("result5");
 var pResult = [pResult1,pResult2,pResult3,pResult4,pResult5]

 function checkBox() {
    /*var aFlor = [2.8,"Florida","Science"];   
    var bGeo = [3.5,"Georgia","Business"];
    var cTex = [2.3,"Texas","Health"];
    var dNew = [4.2,"NewYork","Law"];
    var eMic = [3.9,"Michigan","Humanities"];*/
    var boxValue = document.getElementById("searchBox").value;
    var boxFill = [
      function(){listBox('1','Florida state Scholarship','3.5','Florida','Applied Sciences')},
      function(){listBox('2','Great Achievers Scholarship','4.0','Texas','Health')},
      function(){listBox('3','Helpful Future Scholarship','3.0','Georgia','Business')},
      function(){listBox('4','Never Give Up Scholarship','2.0','Michigan','Humanities')},
      function(){listBox('5','Times Square Talent Scholarship','3.5','New York','Law')}
    ]

  if  (boxValue.includes("f")) {
       for (i=0;i<boxFill.length+1;i++) {
        boxFill[i]();
       }
function listBox(number,name,gpa,state,major) { 
    pResult[number].innerHTML = 
"<dl><dt>"+number+". "+name+"</dt><dd>- minimum GPA is: "+gpa+"</dd><dd>- You must live in "+state+"</dd><dd>- For the "+major+" major!</dd></dl>";
 }

for循环是否存在直接问题,还是数组本身存在问题?

1 个答案:

答案 0 :(得分:2)

i<boxFill.length+1应该是i<boxFill.length,否则你的循环会比元素再循环一次。

该函数被调用,但它会抛出一个错误,因为它试图访问pResult中不存在的索引。如果您打开浏览器的控制台,则会看到错误,例如

  

无法阅读属性&inner;内部HTML&#39;未定义的

JavaScript中的数组是零索引。这意味着pResult[0]将访问第一个元素,pResult[1]访问第二个元素等。

现在,boxFill中的最后一个函数试图访问pResult[5],即第六个元素。但pResult只有五个元素!

您需要将值0传递给4listBox,而不是1传递给5

var boxFill = [
  function(){listBox(0,'Florida state Scholarship','3.5','Florida','Applied Sciences')},
  function(){listBox(1,'Great Achievers Scholarship','4.0','Texas','Health')},
  function(){listBox(2,'Helpful Future Scholarship','3.0','Georgia','Business')},
  function(){listBox(3,'Never Give Up Scholarship','2.0','Michigan','Humanities')},
  function(){listBox(4,'Times Square Talent Scholarship','3.5','New York','Law')}
]

或者,如果您想传递1-5,则需要在访问索引时减去1

pResult[number-1].innerHTML = ...;