¿Por qué JavaScript devuelve la longitud de matriz incorrecta?Array Javascript Problema
var myarray = ['0','1'];
delete myarray[0];
alert(myarray.length); //gives you 2
¿Por qué JavaScript devuelve la longitud de matriz incorrecta?Array Javascript Problema
var myarray = ['0','1'];
delete myarray[0];
alert(myarray.length); //gives you 2
El "eliminar" no modifica la matriz, pero los elementos en la matriz:
# x = [0,1];
# delete x[0]
# x
[undefined, 1]
Lo que se necesita es array.splice
que tienen que utilizar Array.splice - ver http://www.w3schools.com/jsref/jsref_splice.asp
myarray.splice(0, 1);
Esto, a continuación retirar el primer elemento
Según this docs el operador delete no cambia la longitud ofth eArray. Puede usar empalme() para eso.
De la documentación del MDC de matriz:.
"Cuando se elimina un elemento de matriz, la longitud matriz no se ve afectada Para ejemplo, si se elimina un [3], una [4] es todavía a [4] y a [3] no están definidos. Este se mantiene incluso si elimina el último elemento de la matriz (elimine a [a.length-1]). "
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array
Esa es la comportamiento normal. La función delete() no elimina el índice, solo el contenido del índice. Entonces todavía tiene 2 elementos en la matriz, pero en el índice 0 tendrá undefined
.
Usted puede hacer esto con el método John Resig 's agradable remove():
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);
};
que
// 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);
sí. El otro código también elimina el artículo. Pero no actualiza la longitud. –