2011-05-13 43 views
6

Estoy trabajando en una aplicación web ExtJS y estaba buscando una forma de listar todos los nombres de propiedad de un objeto. Buscando en Google, encontré rápidamente un código de referencia en this blog. Ahora, cuando uso este método de claves(), encuentro algún comportamiento extraño al enumerar los nombres de propiedad de un objeto de objetos. Código de ejemplo:Encontrar claves de objetos en Javascript

keys = function(obj) { 
    if (typeof obj != "object" && typeof obj != "function" || obj == null) { 
     throw TypeError("Object.keys called on non-object"); 
    } 
    var keys = []; 
    for (var p in obj) 
     obj.hasOwnProperty(p) && keys.push(p); 
    return keys; 
}; 

var test = {} 
test["nr1"] = {testid: 1, teststr: "one"}; 
test["nr2"] = {testid: 2, teststr: "two"}; 
test["nr3"] = {testid: 3, teststr: "three"}; 
for (var i in keys(test)) { 
    console.log(i); 
} 

Cuando se ejecuta este código, las salidas de la consola:

0 
1 
2 
remove() 

Por lo tanto, en la parte superior de los 3 nombres de las propiedades esperadas, también enumera una función "eliminar()". Esto está claramente relacionado con ExtJS, porque la enumeración funciona como se espera en una página de carga en blanco que no sea de ExtJS.

¿Alguien puede explicarme qué hace exactamente ExtJS aquí? ¿Hay una mejor manera de enumerar los nombres de propiedad propios del objeto?

gracias un montón, wwwald

+7

ExtJS parece haber añadido una función para el prototipo de matriz –

Respuesta

3

Sí, como dijo @Thai, no uso for..in, como cualquier matriz es un objeto y potencialmente podría tener diferentes adiciones en diferentes marcos.

keys = function(obj) { 
    if (typeof obj != "object" && typeof obj != "function" || obj == null) { 
     throw TypeError("Object.keys called on non-object"); 
    } 
    var keys = []; 
    for (var p in obj) 
     obj.hasOwnProperty(p) && keys.push(p); 
    return keys; 
}; 

var test = {} 
test["nr1"] = {testid: 1, teststr: "one"}; 
test["nr2"] = {testid: 2, teststr: "two"}; 
test["nr3"] = {testid: 3, teststr: "three"}; 
document.writeln('<pre>'); 
document.writeln('Current method'); 
for (var key in keys(test)) { 
    document.writeln(key); 
} 


document.writeln('Better method1'); 
for (var arr=keys(test), i = 0, iMax = arr.length; i < iMax; i++) { 
    document.writeln(arr[i]); 
} 

document.writeln('Better method2'); 
Ext.each(keys(test), function(key) { 
    document.writeln(key); 
}); 
document.writeln('</pre>'); 
+0

@see http://jsfiddle.net/xaFXR/5/ – gaRex

+0

Ah, ahora veo. Gracias por señalar la diferencia. ¡La solución de Ext.each() parece perfecta! – wwwald

4

intenta comprobar hasOwnProperty a sólo propiedades de la lista de la matriz en sí, no su prototipo.

for (var i in keys(test)) { 
    if(keys(test).hasOwnProperty(i)){ 
     console.log(i); 
    } 
} 
1

keys(test) devuelve una matriz, por lo que se espera utilizar el clásico para-init condición de próxima loopm y no el bucle for-in.

(function(arr) { 
    for (var i = 0; i < arr.length; i ++) { 
     console.log(i); 
    } 
})(keys(test)); 
Cuestiones relacionadas