Why is JavaScript returning the wrong array length?
var myarray = ['0','1'];
delete myarray[0];
console.log(myarray.length); //gives you 2
Why is JavaScript returning the wrong array length?
var myarray = ['0','1'];
delete myarray[0];
console.log(myarray.length); //gives you 2
Share
Improve this question
edited Jun 16, 2024 at 8:22
dumbass
27.2k4 gold badges36 silver badges73 bronze badges
asked Jan 21, 2010 at 11:00
user255692user255692
6 Answers
Reset to default 13The "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
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
According to this docs the delete operator does not change the length ofth earray. You may use splice() for that.
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
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);
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
.