我如何提取数组中的元素,甚至? [英] How do I extract even elements of an Array?

查看:122
本文介绍了我如何提取数组中的元素,甚至?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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;
}

alert(even(arr));

http://jsbin.com/unocar/2/edit

我已经为了尝试这个code到数组的输出偶数(指数)的元素。它的工作原理,但它也可以输出一些空元素。我该如何解决这个问题code只输出现有的要素是什么?

I have tried this code in order to output even (index) elements of an array. It works, but it also outputs some empty elements. How do I fix this code to output only existing elements?

推荐答案

无论是使用模量:

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

或通过增加每跳过第二个元素 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]);
}

注意:您的code,其实需要用的的从数组索引的元素。如果这是你想要的,你必须使用我%2 === 1 VAR I = 1 分别。

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.

这篇关于我如何提取数组中的元素,甚至?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆