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循环是否有直接问题,或者数组本身是否有问题?

最佳答案

i<boxFill.length+1应为i<boxFill.length,否则循环将重复迭代比元素多一倍的时间。

该函数被调用,但是将引发错误,因为它试图访问pResult中不存在的索引。如果您打开浏览器的控制台,应该会看到如下错误:


  无法读取未定义的属性“ innerHTML”


数组在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 = ...;

07-28 07:21