How do I extract even elements of an Array?

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

提交回复
热议问题