How do I extract even elements of an Array?

前端 未结 8 1914
时光取名叫无心
时光取名叫无心 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:27

    Even if this question is quite old, I would like to add a one-liner filter:
    Odd numbers: arr.filter((e,i)=>i%2)
    Even numbers: arr.filter((e,i)=>i%2-1)
    A more 'legal' way for even numbers: arr.filter((e,i)=>!(i%2))

    There's no need to check with i%2===1 like sumit said; as mod 2 already returns a 0 or a 1 as numbers, they can be interpreted as boolean values in js.

    0 讨论(0)
  • 2020-12-03 14:28

    You need to test the elements for evenness like this:

    var arr = [4,5,7,8,14,45,76];
    
    function even(a){
      var ar = [];
    
      for (var i=0; i<a.length;i++){
        if (a[i] % 2 === 0)
        {
          ar.push(a[i]);
        }
    
      }
    
    return ar;
    }
    
    alert(even(arr));
    

    %2 is the modulo operator, it returns the remainder of integer division.

    0 讨论(0)
提交回复
热议问题