Perché JavaScript restituisce la lunghezza dell'array errata?Problemi con la matrice Javascript
var myarray = ['0','1'];
delete myarray[0];
alert(myarray.length); //gives you 2
Perché JavaScript restituisce la lunghezza dell'array errata?Problemi con la matrice Javascript
var myarray = ['0','1'];
delete myarray[0];
alert(myarray.length); //gives you 2
Il "delete" non modifica la matrice, ma gli elementi nel la matrice:
# x = [0,1];
# delete x[0]
# x
[undefined, 1]
Quello che vi serve è array.splice
è necessario utilizzare Array.splice - vedere http://www.w3schools.com/jsref/jsref_splice.asp
myarray.splice(0, 1);
Questo sarà quindi rimuovere il primo elemento
Secondo this docs l'operatore delete non cambia la lunghezza ofth earray. Puoi usare splice() per quello.
Dalla documentazione MDC di Array:.
"Quando si elimina un elemento di array, la lunghezza matrice non è influenzato Ad esempio, se si elimina un [3], un [4] è ancora a [4] e a [3] non sono definiti. Questo contiene anche l'ultimo elemento dell'array (eliminare a [a.length-1]). "
https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array
Questo è il comportamento normale La funzione delete() non elimina l'indice, ma solo il contenuto dell'indice. Quindi hai ancora 2 elementi nella matrice, ma nell'indice 0 avrai undefined
.
Si può fare questo con il metodo John Resig s' bello 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);
};
di
// 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ì. L'altro codice rimuove anche l'oggetto. Ma non aggiorna la lunghezza. –