Wednesday, July 2, 2008

Good practice in array deletion in JavaScript

It is really piss me off when I spent a few hours trying to find the failure in my JavaScript code.

Eventually, I found out what the problem was. I did not delete my array correctly.


var arr = [1, 2, 3, 4];
for (var i=0; i<arr.length; i++)
arr.splice(i, 1);


This for loop never delete all the elements in your array. When i = 0, arr[0] (a) is deleted and when i = 1, arr[1] (c) is deleted and then exit the loop cause i eqauls arr.length equals 2.

To deal with this problem, you should assing arr.length to one variable so when you delete the array it does not effect you loop.


var arr = [1, 2, 3, 4];
for (i=0, len=arr.length; i<len; i++)
arr.splice(0,1);


Hope this help.

No comments: