开发者

Find Javascript array length without deleted items

Just a simp开发者_运维知识库le 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


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);
};


If for some reason you do want to use sparse arrays (totally legitimate) but want to count the number of defined elements, you can just use reduce(), for example:

var arr = [1, 2, undefined, 3, undefined, undefined, 4];
arr.reduce(function(prev, curr) {
  return typeof curr !== "undefined" ? prev+1 : prev;
}, 0); // evaluates to 4

reduce() is supported by all modern browsers, IE9+. For older browsers there's a polyfill and more info over at MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce


You can use for..in loop, which ommits deleted items.

var a = [1,2,3,4,5];
delete a[0];
delete a[1];

for(var i=0;i<a.length;i++){}
console.log(i); //5

var j=0;
for(var i in a){j++;}
console.log(j); //3


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜