How do I extract even elements of an Array?

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

提交回复
热议问题