gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 13:45:28 25 4
gpt4 key购买 nike

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 中的索引那不存在。如果您打开浏览器的控制台,您应该会看到诸如

之类的错误

Cannot read property 'innerHTML' of undefined

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

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

您需要传递值 04listBox ,不是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 = ...;

关于javascript - For 循环不执行数组中的最后一个函数(JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41435680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com