tags:

views:

531

answers:

5

Oks..

I have an object:

data.Dealer.car[0]
               [1]
               [2]

If I do this:

alert(data.Dealer.car.length);
delete data.Dealer.car[1];
alert(data.Dealer.car.length);

It gives me the same count each time from the alert, even though the actual array element now doesn't exist?

Any ideas?

+3  A: 

JavaScript arrays aren't sparse, if you have a 0 and a 2, then element 1 must exist. Meaning the count is going to be 2.

Ray Hidayat
Yeah, and the element 2 will be undefined .
e-satis
What happens when you delete something at the last index in the array?
Outlaw Programmer
The length will be untouched if you delete the last element. You can set the length to shrink the array to any size you want.
Ates Goral
+4  A: 

If you want to remove an item, use the splice method:

alert(data.Dealer.car.length);
data.Dealer.car.splice(1, 1);
alert(data.Dealer.car.length);

But notice that the indices have changed.

Gumbo
A: 

Array.shift() would remove the first item from the array and make it shorter. Array.pop() will remove the last item.

Jeremy French
+1  A: 

I think you're looking for this:

var arr = [0,1,2,3,4];

alert( arr.splice( 2, 1 ) ); // alerts 2, the element you're removing
alert( arr ) // alerts 0,1,3,4  - the remaining elements

here's a MDC reference

meouw
A: 

Ok.. fixed this now as the array was still allocated.

I needed to basically do:

var newCar = new Array();
for (i = 0 ; i < tblSize -2; i ++)
{
    newCar[i]=data.Dealer.car[i];
}
data.Dealer.car = newCar;
joe90
You want to remove the last item? Just use: data.Dealer.car.pop();
some