[英]JavaScript - Looping array less than I should
I'm trying to loop an array which contains a list of elements returned by ClassName, but I can't loop all of them, because of the next situation: 我正在尝试循环一个包含ClassName返回的元素列表的数组,但是由于下一种情况,我无法循环所有元素:
var list = document.getElementsByClassName('class');
for (var i = 0; i < list.length; i++) {
var theClass = list[i].className; //once got list[i].
theClass = theClass.replace('class', '');
list[i].className = theClass; //twice got list[i].
}
If the size of the list is = 4, I just can loop two times, because I'm getting twice each position per loop. 如果列表的大小= 4,则我只能循环两次,因为每个循环的每个位置都会得到两次。 Do you know what I can do and why it happens?
您知道我能做什么,为什么会发生吗? Thank you.
谢谢。
The data structure returned by getElementsByClassName is Array-like and dynamic based on the DOM. getElementsByClassName返回的数据结构类似于Array,并且基于DOM是动态的。 Once you replace the class on the list item in question, you end up losing an item per iteration.
一旦替换了有问题的列表项上的类,最终每次迭代都会丢失一个项。
To fix this, you can take a copy of the returned values first before operating on them, or work backwards. 要解决此问题,您可以先对返回值进行复制,然后再对它们进行操作,或者向后工作。
Take a copy: 复印:
var list = document.getElementByClassName('class')
var realList = []
Array.prototype.push.apply(realList, list)
for (var i = 0; i < realList.length; i++) {
// do changes as you have already
}
Working backwards: 向后工作:
var list = document.getElementsByClassName('class')
for (i=list.length - 1; i >= 0; i--) {
// do changes to list[i]
}
Another poster briefly mentioned a while loop which also works, but then their answer disappeared (I don't want to take credit for this!): 另一位张贴者简短地提到了一个while循环,该循环也有效,但随后他们的答案消失了(我不想为此感到遗憾!):
var list = document.getElementsByClassName('class')
while (list.length != 0) {
// do changes to list[0]
}
If you write out what happens in your initial code, you can see the problem more clearly: 如果您写出初始代码中发生的情况,则可以更清楚地看到问题:
Iteration 1: i=0, list=[a,b,c,d], length = 4, list[i]=a
Iteration 2: i=1, list=[b,c,d], length = 3, list[i]=c
Before Iteration 3: list=[b,d], i=2, length = 2, loop breaks
Now writing out what happens when using the reverse loop: 现在写出使用反向循环时发生的情况:
Iteration 1: i=3, list=[a,b,c,d], length = 4, list[i]=d
Iteration 2: i=2, list=[a,b,c], length = 3, list[i]=c
Iteration 3: i=1, list=[a,b], length = 2, list[i]=b
Iteration 4: i=0, list=[a], length = 1, list[i]=a
All these solutions are variations on this solution of avoiding using i to reference the middle parts of the array-like result value of getElementsByClassName so that the dynamic nature of it is dealt with. 所有这些解决方案都是该解决方案的变体,避免使用i来引用getElementsByClassName的类似于数组的结果值的中间部分,以便处理其动态性质。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.