简体   繁体   English

早期破环的JavaScript

[英]JavaScript For Loop Breaking Early

Why would a for loop terminate early in JavaScript? 为什么for循环会在JavaScript中提前终止? For some reason my outer for loop terminates after the first repetition. 由于某种原因,我的外部for循环在第一次重复后终止。 I am new to JavaScript but would expect something like this to work in Java. 我是JavaScript新手,但希望Java这样的东西能正常工作。

function check(){
    var elements = document.getElementById('fields').children;
    var filteredMolecules = molecules;
    console.log(elements.length);
    for (i = 0; i < elements.length; i++) { 
        console.log(elements[i].id)
        filterMolecules(filteredMolecules, elements[i].id, 0, 10);
    }
}

function filterMolecules(molecules, parameter, lower, upper){
    console.log('filtering');
    var filteredMolecules = [];
    for (i=0;i<molecules.length;i++){
        var value = molecules[i].val()[parameter];
        filteredMolecules.push(molecules[i]);
    }
    molecules=filteredMolecules;
}

In check(), I loop through elements which contains 22 items as shown by the first console.log(elements.length). 在check()中,我遍历包含22个项目的元素,如第一个console.log(elements.length)所示。 If I remove the method filterMolecules(...) then all 22 IDs are logged. 如果删除方法filterMolecules(...),则会记录所有22个ID。 However, with the code as is, only the first id is logged. 但是,按原样使用代码,仅记录第一个ID。

I believe the filterMolecules method which should run elements.length number of times is causing the outer for loop to not work. 我相信应该运行elements.length次的filterMolecules方法导致外部for循环不起作用。 Could someone please explain why this is happening. 有人可以解释为什么会这样。 If relevant, in filterMolecules(...) the data is retrieved from Google Firebase with molecules[i].val()[parameter]. 如果相关的话,在filterMolecules(...)中,使用molecular [i] .val()[parameter]从Google Firebase检索数据。 Additionally, both methods use the global variable molecules (line 3 and line 14) 此外,两种方法都使用全局变量分子(第3行和第14行)

When you don't declare variables in javascript you end up using globals (which can be a difficult to spot source of bugs). 如果您未在javascript中声明变量,则最终会使用全局变量(这可能很难发现bug的来源)。 So here you are using the same global variable i for both loops. 因此,在这里,两个循环都使用相同的全局变量i When you start looping thought molecules you are accidentally incrementing the counter loop of your first for . 当您启动循环思维molecules您意外增加你的第一个柜台循环for Use different variables or define them with : 使用其他变量使用以下变量定义它们:

 for (let i=0;i<molecules.length;i++)

Which will give each loop its own version of i . 这将为每个循环提供其自己的i版本。

In this case, since the declarations are inside individual functions, you could use var too: 在这种情况下,由于声明位于各个函数内部,因此您也可以使用var

for (var i=0;i<molecules.length;i++) {
 // etc.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM