2010-01-21 11 views

risposta

13

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

5

è necessario utilizzare Array.splice - vedere http://www.w3schools.com/jsref/jsref_splice.asp

myarray.splice(0, 1); 

Questo sarà quindi rimuovere il primo elemento

+2

sì. L'altro codice rimuove anche l'oggetto. Ma non aggiorna la lunghezza. –

1

Secondo this docs l'operatore delete non cambia la lunghezza ofth earray. Puoi usare splice() per quello.

0

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.

1

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);