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

sha*_*ngh 7 javascript arrays data-structures

我有一个数组,就像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);
}
};
Run Code Online (Sandbox Code Playgroud)

但它没有用.

Pra*_*lan 13

使用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);
Run Code Online (Sandbox Code Playgroud)


如果要更新现有阵列,请执行以下操作.

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);
Run Code Online (Sandbox Code Playgroud)


另一种以相反顺序迭代循环的方法(从最后一个元素到第一个元素).

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);
Run Code Online (Sandbox Code Playgroud)


UDI*_*DID 7

您可以通过执行此操作删除所有备用索引

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);
Run Code Online (Sandbox Code Playgroud)

或者如果你想存储在不同的数组中,你可以这样做.

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);
Run Code Online (Sandbox Code Playgroud)