Deleting undefined indexes in array Javascript

时间:2017-04-10 00:30:33

标签: javascript arrays undefined

I can't delete all the undefined indexes in this array.I do console.log and it shows me [undefined, 2].

var array = [];
array[1] = 2;
array[3] = 4;

for(var i = 0; i < array.length; i ++) {
  if(array[i]) {

  } else {
    array.splice(array.indexOf(array[i]), 1);
  }
}

console.log(array)

1 个答案:

答案 0 :(得分:0)

var array = [];
array[1] = 2;
array[3] = 4;

for(var i = 0; i < array.length; i ++) {
  if(array[i]) {

  } else {
    array.splice(i, 1);
  }
}

console.log(array)