如何从数组中删除所有奇数索引(例如:a [1]、a [3]..)的值

13

我有一个数组,例如var aa = ["a","b","c","d","e","f","g","h","i","j","k","l"]; 我想要删除位于偶数索引位置上的元素,输出结果应该是 aa = ["a","c","e","g","i","k"];

我尝试过以下方法

for (var i = 0; aa.length; i = i++) {
if(i%2 == 0){
    aa.splice(i,0);
}
};

但它没有起作用。


6
aa = aa.filter(function (v,i) { return !(i%2); }); - Jaromanda X
@Rajesh,不会的。 - Aleksey L.
无论你做什么,除非将数组缩小到零长度,否则for循环将永远运行或直到出现异常... aa.length始终为“真值”。 - Jaromanda X
7个回答

18

使用 Array#filter 方法

var aa = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"];

var res = aa.filter(function(v, i) {
  // check the index is odd
  return i % 2 == 0;
});

console.log(res);

如果您想要更新现有的数组,请像这样进行操作。

var aa = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"],
    // variable for storing delete count
  dCount = 0,
    // store array length
  len = aa.length;

for (var i = 0; i < len; i++) {
  // check index is odd
  if (i % 2 == 1) {
    // remove element based on actual array position 
    // with use of delete count
    aa.splice(i - dCount, 1);
    // increment delete count
    // you combine the 2 lines as `aa.splice(i - dCount++, 1);`
    dCount++;
  }
}


console.log(aa);


通过另一种方式按相反的顺序迭代for循环(从最后一个元素到第一个元素)。


var aa = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"];

// iterate from last element to first
for (var i = aa.length - 1; i >= 0; i--) {
  // remove element if index is odd
  if (i % 2 == 1)
    aa.splice(i, 1);
}


console.log(aa);


1
要更新现有的数组,只需使用aa = aa.filter而不是var res = aa.filter - Jaromanda X
查看问题-不需要参考资料 - Jaromanda X

13

通过这种方式,您可以删除所有备用索引

var aa = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"];

for (var i = 0; i < aa.length; i++) {
  aa.splice(i + 1, 1);
}

console.log(aa);

or if you want to store in a different array you can do like this.

var aa = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"];

var x = [];
for (var i = 0; i < aa.length; i = i + 2) {
  x.push(aa[i]);
}

console.log(x);


嗨,你这边会进入无限循环吗? - UDID

4
你可以使用.filter()
 aa =  aa.filter((value, index) => !(index%2));

2
aa = aa. ... 作为过滤器返回一个新数组,不会改变原始数组。 - Jaromanda X

2
您可以像下面这样使用临时变量。
var a = [1,2,3,4,5,6,7,8,9,334,234,234,234,6545,7,567,8]

var temp = [];
for(var i = 0; i<a.length; i++)
   if(i % 2 == 1)
      temp.push(a[i]);

a = temp;

1
在ECMAScript 6中,
var aa = ["a","b","c","d","e","f","g","h","i","j","k","l"];
var bb = aa.filter((item,index,arr)=>(arr.splice(index,1)));
console.log(bb);

0

我在这里读到splice的时间复杂度为O(N)。 不要在循环中使用它!

一个简单的替代方法是就地删除奇数索引:

for (let idx = 0; idx < aa.length; idx += 2)
    aa[idx >> 1] = aa[idx];
aa.length = (aa.length + 1) >> 1;

我使用x >> 1作为Math.floor(x/2)的快捷方式。


0
const aa = ["a","b","c","d","e","f","g","h","i","j","k","l"];
let bb = aa.filter((items, idx) => idx % 2 !== 0)

2
你能详细说明一下你的回答吗?它看起来不完整。 - cloned

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接