user255692
user255692

Reputation:

Why does deleting an element from the array not change the array’s length?

Why is JavaScript returning the wrong array length?

var myarray = ['0','1'];
delete myarray[0];
console.log(myarray.length); //gives you 2

Upvotes: 7

Views: 1537

Answers (6)

edigu
edigu

Reputation: 10099

You can do this with John Resig's nice remove() method:

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

than

// Remove the second item from the array
array.remove(1);
// Remove the second-to-last item from the array
array.remove(-2);
// Remove the second and third items from the array
array.remove(1,2);
// Remove the last and second-to-last items from the array
array.remove(-2,-1);

Upvotes: 1

rogeriopvl
rogeriopvl

Reputation: 54056

That's the normal behavior. The delete() function does not delete the index, only the content of the index. So you still have 2 elements in the array, but at index 0 you will have undefined.

Upvotes: 0

Otto Allmendinger
Otto Allmendinger

Reputation: 28268

The "delete" doesn't modify the array, but the elements in the array:

 # x = [0,1];
 # delete x[0]
 # x
 [undefined, 1]

What you need is array.splice

Upvotes: 13

Yoni
Yoni

Reputation: 10321

From Array's MDC documentation:

"When you delete an array element, the array length is not affected. For example, if you delete a[3], a[4] is still a[4] and a[3] is undefined. This holds even if you delete the last element of the array (delete a[a.length-1])."

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator

https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array

Upvotes: 1

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103135

According to this docs the delete operator does not change the length ofth earray. You may use splice() for that.

Upvotes: 1

Niko
Niko

Reputation: 6269

you have to use array.splice - see http://www.w3schools.com/jsref/jsref_splice.asp

myarray.splice(0, 1);

this will then remove the first element

Upvotes: 5

Related Questions