Find javascript array length without deleted elements

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

myArray.length ()

The above information will return the length, including deleted items. How to get length without deleted items? Thanks

EDIT:

Thanks for answers. I delete the entry “delete myarray [0]” and it works well. Other sections of the script rely on the length () method to return the length, including deletion. The splicing method looks the way I want, so I will try this

+5
source share
4 answers

I think you are deleting the elements of an array using an operator delete.

, , :

var a = [1,2,3];

delete a[0];

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

, splice:

var a = [1,2,3];

a.splice(0,1);

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

:

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

( jQuery) , () Javascript. delete, .

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

+1

- ( ), , reduce(), :

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() IE9+. polyfill MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

+1
source

You can use for..in loop which removes elements.

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
+1
source

All Articles