How do I extract even elements of an Array?

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

    I just wanted to explain why your result is not what you expected since everyone else shows excellent solutions. You are iterating over an array size N so your resulting array will attempt to push elements in an array that will result in size N. Since only N/2 will be found in the original array your resulting array will fill the rest with blanks to fill in the rest of N. So if you checked to see if a[2*i] exists OR checked to see if a[i] % 2 == 0 before inserting, your resulting array will contain only the even indexed values

    0 讨论(0)
  • 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])
    }
    
    0 讨论(0)
  • 2020-12-03 14:20
    var arr = [4,5,7,8,14,45,76];
    
    function even(a)
    {
      var ar = [];  
    
      for (x in a)
      {
    
        if((a[x]%2)==0)
        ar.push(a[x]);  
    
      }
    return ar;
    }
    
    alert(even(arr));
    
    0 讨论(0)
  • 2020-12-03 14:21

    For IE9+ use Array.filter

    var arr = [4,5,7,8,14,45,76];
    var filtered = arr.filter(function(element, index, array) {
      return (index % 2 === 0);
    });
    

    With a fallback for older IEs, all the other browsers are OK without this fallback

    if (!Array.prototype.filter)
    {
      Array.prototype.filter = function(fun /*, thisp */)
      {
        "use strict";
    
        if (this === void 0 || this === null)
          throw new TypeError();
    
        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof fun !== "function")
          throw new TypeError();
    
        var res = [];
        var thisp = arguments[1];
        for (var i = 0; i < len; i++)
        {
          if (i in t)
          {
            var val = t[i]; // in case fun mutates this
            if (fun.call(thisp, val, i, t))
              res.push(val);
          }
        }
    
        return res;
      };
    }
    
    0 讨论(0)
  • 2020-12-03 14:24

    Either use modulus:

    for (var i = 0; i < a.length; i++) {
        if(i % 2 === 0) { // index is even
            ar.push(a[i]);
        }
    }
    

    or skip every second element by incrementing i accordingly:

    for(var i = 0; i < a.length; i += 2) {  // take every second element
        ar.push(a[i]);
    }
    

    Notice: Your code actually takes the elements with odd indexes from the array. If this is what you want you have to use i % 2 === 1 or start the loop with var i = 1 respectively.

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

    This will work on 2018 :)

    take the odd indexes and apply to filter

    var arr = [4, 5, 7, 8, 14, 45, 76,5];
    let filtered=arr.filter((a,i)=>i%2===1);
    console.log(filtered);

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