最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Find Javascript array length without deleted items - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question edited Oct 15, 2009 at 4:36 Lobe asked Oct 15, 2009 at 4:19 LobeLobe 53810 silver badges25 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 14

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)

  1. 暂无评论