[英]how do I select only the odd or even variables that used in a for loop?
這是我的JS代碼:
for (var i=0;i<document.getElementsByClassName('box').length ;i++) {
//code here
}
我想知道如何只選擇奇數或偶數
偶數數字具有這種奇怪的屬性(甚至是奇數數字),加上它們使它們保持均勻(或奇數)。
for (var i = 0; i < document.getElementsByClassName('box').length; i += 2) {} // even
for (var i = 1; i < document.getElementsByClassName('box').length; i += 2) {} // odd
注意,如果沒有充分的理由一遍又一遍地評估getElementByClassName
,我會把它移到循環之外。
使用數組操作圖
var boxes = document.getElementsByClassName('box');
boxes.forEach(function(box, index) {
if (index % 2 === 0) {
//even elements are here, you can access it by box
} else {
//odd elements are here, you can access it by box
}
});
或者簡單的循環
for (var i=0;i<document.getElementsByClassName('box').length ;i++) {
if ( i % 2 === 0) { even }
else { odd }
}
更新
正如@Motti所說,。map,forEach(或任何數組操作)不能用於HTMLCollection,你可能需要做的是:
Array.prototype.slice.call(boxes).forEach(function(box, index){
if (index % 2 === 0) { //even box }
else { //odd box }
})
喜歡@stvnBrkdll說
for (var i=0;i<document.getElementsByClassName('box').length ;i++) {
if (i % 2 === 0) {} // this are the even no.s
}
看一下這個
function isOdd(num) { return num % 2;}
for (var i=0;i<ocument.getElementsByClassName('box').length;i++) {
if(isOdd(i))
{
// Code goes here when i is odd
}
else
{
// Code goes here when i is even
}
}
最好使用querySelectorAll()
代替NodeLists和Live HTMLCollections的詳細信息。 並使用let
而不是var
。
確定循環當前是偶數還是奇數迭代的最簡單方法是使用2的模數:
if ( i % 2 === 0) {
... // do whatever for even counts
} else {
...// otherwise it's an odd iteration if it isn't even
}
var NodeList = document.querySelectorAll('.box'); for (let i=0; i<NodeList.length; i++) { if (i % 2 === 0) { NodeList[i].textContent +="\\nEVEN"; } else { NodeList[i].textContent +="\\nODD"; } }
.box { height:40px; width:40px; border:1px solid black }
<div class='box'>BOX</div><b>The count starts at 0 so second box is odd. This can easily be adjusted at the for loop</b> <div class='box'>BOX</div><div class='box'>BOX</div><div class='box'>BOX</div><div class='box'>BOX</div><div class='box'>BOX</div><div class='box'>BOX</div><div class='box'>BOX</div><div class='box'>BOX</div><div class='box'>BOX</div><div class='box'>BOX</div><div class='box'>BOX</div><div class='box'>BOX</div><div class='box'>BOX</div><div class='box'>BOX</div><div class='box'>BOX</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.