How do I extract even elements of an Array?

前端 未结 8 2018
时光取名叫无心
时光取名叫无心 2020-12-03 13:47
var arr = [4, 5, 7, 8, 14, 45, 76];

function even(a) {
  var ar = [];

  for (var i = 0; i < a.length; i++) {
    ar.push(a[2 * i + 1]);
  }

  return ar;
}

ale         


        
8条回答
  •  我在风中等你
    2020-12-03 14:13

    why don't you try with the % operator. It gives you the remaining of a division.

    replace the loop block with

    if ((i % 2) === 0) {
        ar.push(a[i])
    }
    

提交回复
热议问题