2017-01-03 55 views
0

未執行boxFill()數組中的最後一個函數。我試着考慮陣列的長度,但沒有運氣。 (我對js很新,只是說)。它遍歷前四個索引,並且始終不執行最後一個索引,即使當我更改索引的位置時也是如此。For循環未執行數組中的最後一個函數(JavaScript)

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循環或者是它的東西在陣列本身?

+2

'我

+0

還有更直接的方法來完成我認爲你想要做的事情,使用一組對象和一個函數來輸出你的數據,而不是5個函數並手動編號。 – Shazam

回答

2

i<boxFill.length+1i<boxFill.length,否則你的循環迭代之外還有元素一次。

函數被調用,而是因爲它試圖在pResult不存在訪問索引就會拋出一個錯誤。如果你打開瀏覽器的控制檯,您應該看到一個錯誤,如

無法讀取的不確定

財產「的innerHTML」

數組是在JavaScript 零索引。這意味着,pResult[0]將訪問的第一個元素,pResult[1]訪問第二元件等

現在,在boxFill的最後一個函數試圖訪問pResult[5],即第六元件。但pResult只有五個元素!

您需要0值傳遞給4listBox,不15

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 = ...; 
+0

或者調用'boxFill [i + 1]()'(並在之後執行-1位)。 ;-) – RobG

+0

好吧,我現在看到了。謝謝! –