2

I have array with integer index

myarray[1]=val1
myarray[2]=val2
myarray[4]=val3
myarray[5]=val4

in this case myarray[0] and myarray[3] is undefined and

for (var i in myarray)
{
 console.log(i)
}

output 1,2,4,5

I like to "remove" myarray[2] without shifting others members and that after delete also myarray[2] come to be undefined and output should be 1,4,5

I tred myarray.splice(2,1,undefined) but it's still output index 2

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
BaraBashkaD
  • 144
  • 3
  • 10

3 Answers3

6

Stop stop!

First problem, while yes most things in js are objects, do not iterate over arrays with for in. "for ... in" is for object literals. Use a normal iterative loop for arrays.

Second, delete is intended to delete properties on objects. Again, arrays are objects but this isn't the right use of delete.

If you want to set the value of an array index to undefined, just assign it undefined.

myarray[2] = undefined;

Edit:

The reason you don't use for...in on an array is this:

var x = [1,2,3];
x.test = 'abc';

for(var i in x){
    console.log(x[i]);
}
//1,2,3,abc

for(var i=0; i<x.length; i++){
   console.log(x[i]);
}
//1,2,3

What Dmitry seems to be trying to do is only return indices that have values. Do it like this.

for(var i=0; i<myarray.length; i++){
    if( myarray[i] !== undefined ){
        console.log( myarray[i] );
    }
}

Again, to set an index to undefined you shouldn't use delete. You can, but don't. Just do:

myarray[i] = undefined;

Hope this helps.

Geuis
  • 41,122
  • 56
  • 157
  • 219
  • But look at the desired output. Sounds like a hacky solution is exactly what the OP is looking for. – bfavaretto Oct 02 '13 at 22:09
  • Honestly I can't really understand what's being asked but I'll amend my answer with what I think he's asking about. You should almost never iterate over an array with for...in. It will return any property on the object in addition to the numerical keys. – Geuis Oct 02 '13 at 22:32
  • Any non-enumerable property, yes. What I'm trying to say is that a *sparse* array seems to be desired in this case. The warnings against `for..in` are never undesirable though. – bfavaretto Oct 02 '13 at 22:35
  • I also try to avoid checking is value is undefined in case of for .. in get only relevant indexes and don't use if( myarray[i] !== undefined ) is – BaraBashkaD Oct 03 '13 at 08:27
4

Use delete:

delete myarray[2];
Barmar
  • 741,623
  • 53
  • 500
  • 612
0
delete myArray[2];

Use delete to remove an array index.

>> myArray[2]
undefined

And now you won't iterate over it with your for-in loop.

Also, for-in should only be used for iterating over object's properties. Use a regular for-loop when iterating over arrays.

Jackson
  • 9,188
  • 6
  • 52
  • 77