Why does JavaScript return the wrong array length?
var myarray = ['0','1']; delete myarray[0]; alert(myarray.length); //gives you 2
"delete" does not change the array, but the elements in the array:
# x = [0,1]; # delete x[0] # x [undefined, 1]
You need array.splice
you need to use array.splice - see http://www.w3schools.com/jsref/jsref_splice.asp
myarray.splice(0, 1);
this will remove the first item
According to this document, the delete operator does not change the length of the previous one. You can use splice () for this.
From an Array MDC document:
"When you delete an element of an array, the length of the array does not change. For example, if you delete [3], [4] another [4], and [3] is undefined. This is preserved 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
You can do this using the John Resig nice () 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);
This is normal behavior. The delete () function does not delete the index, but only the contents of the index. So you still have 2 elements in the array, but with index 0 you will have undefined .
undefined