Problem with Javascript Array

Why does JavaScript return the wrong array length?

var myarray = ['0','1']; delete myarray[0]; alert(myarray.length); //gives you 2 
+7
javascript arrays
source share
6 answers

"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

+13
source share

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

+5
source share

According to this document, the delete operator does not change the length of the previous one. You can use splice () for this.

+1
source share

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

+1
source share

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); 
+1
source share

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 .

0
source share

All Articles