2012-09-27 11 views
8

Solo me pregunto, cuando usas array.length, obtiene el último valor de índice y agrega uno. ¿Qué pasa si usted tiene una matriz, que se define de esta manera por alguna razón:¿Cuál es la mejor manera de contar la longitud absoluta de la matriz en JavaScript?

var myArray2 =[]; 
    myArray2[10]='x'; 
    myArray2[55]='x'; 

¿Cuál es la manera más favorable para obtener la longitud real de esta matriz? Algo que devolvería 2 como el valor.

Estaba pensando algo como esto, pero no estoy seguro si ya había un método para esto, o si hay una implementación más rápida.

Array.prototype.trueLength= function(){ 
    for(var i = 0,ctr=0,len=myArray2.length;i<len;i++){ 
     if(myArray2[i]!=undefined){ 
      ctr++; 
     } 
    } 
    return ctr;   
} 
console.log(myArray2.trueLength()); 

Respuesta

10

Array.prototype.reduce caminas s a través de los índices existentes, por lo que puede hacer:

var length = myArray2.reduce(function(sum) { 
    return sum+1; 
}, 0); 

"Pero Uncle Zirak! reduce mató a mis padres!" No se preocupe, joven, podemos utilizar Array.prototype.filter!

var length = myArray2.filter(function(item, idx) { 
    return idx in myArray2; 
}).length; 

"Todo este material matriz es aburrido!" Bueno, Whadya parece este !?

Object.keys(myArray2).length; 

"Pero ... pero ... pero Zirak !!!! ! Estamos Amish, no tenemos todavía ECMAScript 5" No temas, Zirak está aquí

for (var length = 0, i = 0; i < myArray2.length; i++) { 
    if (i in myArray2) { 
     length += 1; 
    } 
} 

Pero en momentos como éste, uno tiene que preguntarse: ¿Por qué todo eso y desafiar a los fines de la matriz, una construcción estructurada, en lugar de utilizar algo ajuste más para su propósito?

+2

Bueno, eso es elegante. –

+0

Niza. por supuesto, usted' d necesita una implementación de 'Array.prototype.reduce' para IE <9 –

+0

@TimDown Compen saciado por eso (y algunos más). – Zirak

2

Iterar a través de una matriz usando for in. jsfiddle

Array.prototype.trueLength= function(){ 
    var ctr = 0; 
    for(var i in this){ 
     if(this.hasOwnProperty(i)){ 
      ctr++; 
     } 
    } 
    return ctr;   
} 
console.log(myArray2.trueLength()); 
1

método alternativo Prototipo:

Array.prototype.trueLength= function(){ 
    var list= [], ctr = 0, array = this; 

    for(var i in array) (function(arr) { 

     if(array.hasOwnProperty(i)){ 
      list.push(arr); 
      ctr++; 
     }; 


    }(array[i])); 

    return {length: ctr, "list": list} 
} 

muestra:

var myArray2 =[]; 
    myArray2[10]='44'; 
    myArray2[55]='55'; 

// list not undefined 
myArray2.trueLength().list // ["44", "55"] 

// not undefined length list 
myArray2.trueLength().length // 2 
0

que haría uso de the in operator:

function getArrayPropertyCount(arr) { 
    var count = 0; 
    for (var i = 0, len = arr.length; i < len; ++i) { 
     if (i in arr) { 
      ++count; 
     } 
    } 
    return count; 
} 
0
function TrueArrayLength (myArray2) 
{ 
var TrueLength = 0;  
for (var i = 0; i < myArray2.length; i++) 
{ 
    if (i in myArray2) 
    { 
     TrueLength += 1; 
    } 
} 

return TrueLength; 
} 

Utilice esta función y obtener las longitudes reales de la matriz.

Cuestiones relacionadas