2016-03-02 16 views
5

Il seguente codice:javascript: un comportamento imprevisto spinge in array vuoto

var arr1 = [1,2,3]; 
var obj1 = {}; 

for (var j = 0; j < arr1.length; j++) { 
    if (obj1[j.toString()]) 
     obj1[j.toString()] = obj1[j.toString()].push(j) 
    else 
     obj1[j.toString()] = [].push(j); 
} 

ha prodotto il seguente risultato:

obj1 
=> { '0': 1, '1': 1, '2': 1 } 

e vorrei solo gentilmente sapere perché.

(mi rendo conto ora che il seguente codice:

var arr1 = [1,2,3]; 
var obj1 = {}; 

for (var j = 0; j < arr1.length; j++) { 
    if (obj1[j.toString()]) 
     obj1[j.toString()] = obj1[j.toString()].push(j) 
    else { 
     obj1[j.toString()] = []; 
     obj1[j.toString()].push(j); 
    } 
} 

mi darà la mia uscita desiderata:

obj1 
=> { '0': [ 0 ], '1': [ 1 ], '2': [ 2 ] } 

)

+2

Bene, '[]' è uguale a 'Array.prototype', non c'è una matrice vuota e non si preme nulla all'interno di' obj'. Il secondo frammento di codice è il modo corretto di farlo, in cui si crea effettivamente una matrice vuota – adeneo

risposta

11

Perché from the documentation il metodo Array.prototype.push() restituisce la lunghezza Array , non la matrice stessa.

+0

Non ho notato il primo snippet. +1 –

+0

Confermato. [1,2,3] .push (60); // 4; [] .push (90); // 1; Grazie. – anatta

Problemi correlati