suppress array element while iterating it
by Subramanian[ Edit ] 2012-09-21 09:20:47
var a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
for ( var i in a ) {
if ( a[i] == 1 || a[i] == 2 )
a.splice( i, 1 );
}
Print( a ); // prints: 0,2,3,4,5,6,7,8,9
Print( a.length ); // prints: 9
We can use : a[i] == undefined; Or start from the end :
var a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
for ( var i = a.length - 1; i >= 0; i-- ) {
if ( a[i] == 0 || a[i] == 8 )
a.splice( i, 1 );
}
Print( a ); // prints: 1,2,3,4,5,6,7,9
Print( a.length ); // prints: 8