views:

113

answers:

2

Just a simple question that I can't seem to find the answer to.

myarray.length()

The above will return the length including deleted items. How do I get the length without deleted items? Thanks

EDIT:

Thanks for the answers. I am deleting by writing 'delete myarray[0]' and this works well. Other sections of the script rely on the length() method to return the length including deletes. The splice method looks like what I want, so I'll try this

+2  A: 

I think that you are deleting your array elements by using the delete operator.

This operator removes the element at the index you specify, but the array length is not affected, for example:

var a = [1,2,3];

delete a[0];

console.log(a); // results in [undefined, 2, 3]

If you want to delete the elements and shift the indexes, you can use the splice function:

var a = [1,2,3];

a.splice(0,1);

console.log(a); // [2, 3]

You could implement a simple function to remove elements in a given index:

Array.prototype.removeAt = function (index) {
  this.splice(index,1);
};
CMS
+1  A: 

John Resig (author of jQuery) wrote a function that (really) removes items from an array in Javascript. If you use this function instead of the delete operator, you should get an accurate count from the array after the deletion.

http://ejohn.org/blog/javascript-array-remove/

Robert Harvey
Do you know why he did that? It seems to be redundant, performing worse than the standard built-in splice method.
bobince
The method is comprehensive; it uses Splice, but it does some other things also.
Robert Harvey