简体   繁体   English

function 中的第二个 for 循环不起作用

[英]The second for loop in a function doesn't work

I have a function like below:我有一个 function 如下所示:

function launching() {

    let ranges = document.getElementsByClassName('range');
    liczba2 = 0;
    console.log(ranges);

    let czeks = document.getElementsByClassName('check');
    liczba = 0;
    eluwina = 0;

    for (let i = 0; i <= czeks.length; i++) {
        if (czeks[i].checked) {
            liczba ++;
            console.log(liczba);

        }
    }

    for (let n = 0; ranges.length; n++) {
        let val = ranges.getAttribute('value');
        console.log(val);
    }
}

The first for loop works fine.第一个 for 循环工作正常。 However the second one:然而第二个:

for (let n = 0; ranges.length; n++) {
        let val = ranges.getAttribute('value');
        console.log(val);
    }

Doesn't work at all.根本不起作用。 Even if there's just console log after first loop, it won't execute.即使第一次循环后只有控制台日志,它也不会执行。 I'll be grateful if anyone could help me.如果有人可以帮助我,我将不胜感激。 Thanks in advance:).提前致谢:)。

The second loop should be:第二个循环应该是:

 for (let n = 0; n < ranges.length; n++) { let val = ranges[n].getAttribute('value'); console.log(val); }

In your code, if ranges.length == 0 , the loop will end immediately, since the condition ranges.length is falsey.在您的代码中,如果ranges.length == 0 ,循环将立即结束,因为条件ranges.length是错误的。 Otherwise it will be cause an infinite loop, because the value of ranges.length doesn't change, and a non-zero value is truthy.否则会导致死循环,因为ranges.length的值不会改变,非零值是真的。

However, the loop will stop because ranges.getAttribute('value') will get an error.但是,循环将停止,因为ranges.getAttribute('value')会出错。 ranges is a NodeList , not a single element, and it doesn't have a getAttribute() method. ranges是一个NodeList ,而不是单个元素,并且它没有getAttribute()方法。 You need to index it to get the current element in the iteration.您需要对其进行索引以获取迭代中的当前元素。

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

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