如何仅选择 for 循环中使用的奇数或偶数变量?

Kem*_*ldy 2 javascript

这是我的 JS 代码:

for (var i=0;i<document.getElementsByClassName('box').length ;i++) {
//code here
}
Run Code Online (Sandbox Code Playgroud)

我想知道如何只选择奇数或偶数 i

Moh*_*say 5

使用数组操作映射

    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
       }
    });
Run Code Online (Sandbox Code Playgroud)

或者简单的循环

for (var i=0;i<document.getElementsByClassName('box').length ;i++) {
  if ( i % 2 === 0) { even }
  else { odd }
}
Run Code Online (Sandbox Code Playgroud)

更新

正如@Motti 所说,.map、forEach(或任何数组操作)不适用于 HTMLCollection,您可能需要做的是:

 Array.prototype.slice.call(boxes).forEach(function(box, index){
    if (index % 2 === 0) { //even box }
    else { //odd box }
 })
Run Code Online (Sandbox Code Playgroud)