[英]Function call inside a for loop breaks the loop
I have a small fiddle I was experimenting with, and I noticed calling a function inside a for loop condition was stopping the loop. 我正在尝试做一个小提琴,我注意到在for循环条件内调用一个函数正在停止循环。 Basically, initially I wanted to do this: 基本上,最初我想这样做:
// add event listeners to tabs
for (i=0;i<tabs.length;i++) {
tabs[i].addEventListener('click', function(event) {
var tab = event.target;
selectPage(tab.dataset.tab);
changeTab(tab);
});
if (tabs[i].classList.contains('active')) {
selectPage(tabs[i].dataset.tab);
}
}
But, ended up having to do this to make it work: 但是,最终不得不这样做以使其起作用:
// add event listeners to tabs
for (i=0;i<tabs.length;i++) {
tabs[i].addEventListener('click', function(event) {
var tab = event.target;
selectPage(tab.dataset.tab);
changeTab(tab);
});
}
// find active class and set page
for (i=0;i<tabs.length;i++) {
if (tabs[i].classList.contains('active')) {
selectPage(tabs[i].dataset.tab);
}
}
Here is a link to the Fiddle 这是小提琴的链接
Thanks for any help in advance, I feel there is something fundamental here I'm not getting. 感谢您事先提供的帮助,我觉得这里有些基本内容没有得到。 Thanks 谢谢
Lesson 0: use ESLint or similar tools to check your code for trivial errors before spending sleepless nights here on SO and/or in debugging tools. 第0课:使用ESLint或类似工具在SO和/或调试工具上度过不眠之夜之前,请检查代码中是否有小错误。
Lesson 1: localize your variables. 第1课:本地化变量。
Your problem is with variable i
that's global - hence reused by both your global code and selectPage
function. 您的问题出在全局变量i
,因此可以被全局代码和selectPage
函数重用。 The latter sets its value to tabs.length
, ending up the loop prematurely. 后者将其值设置为tabs.length
,过早地结束循环。
Just replace i = 0
with var i = 0
at each for
expression. 只需更换i = 0
与var i = 0
在每一个for
表达。
Try declaring the x variable using let. 尝试使用let声明x变量。
// add event listeners to tabs
for (let i=0;i<tabs.length;i++) {
tabs[i].addEventListener('click', function(event) {
var tab = event.target;
selectPage(tab.dataset.tab);
changeTab(tab);
});
if (tabs[i].classList.contains('active')) {
selectPage(tabs[i].dataset.tab);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.