Visit Mozilla.org

Referencia de JavaScript 1.5:Sentencias:for...in

De MDC


Tabla de contenidos

[editar] Resumen

Itera con una variable especificada sobre todas las propiedades de un objeto, en un orden arbitriario. Para cada una de las propiedades, se ejecuta la sentencia especificada.

Sentencia
Implementada en: JavaScript 1.0, NES 2.0
Versión ECMA: ECMA-262

[editar] Sintaxis

for (variable in objeto)
  sentencia
for (var variable in objeto)
  sentencia

[editar] Parámetros

variable 
Variable que itera sobre cada propiedad, opcionalmente se declara con la palabra clave var. Esta variable es local a la función, no al bucle. (En otras palabras, cuando el bucle termina, la variable tiene el valor de la última propiedad visitada).
objeto 
Objeto cuyas propieddes se iteran.
sentencia 
Una sentencia a ejecutar por cada propiedad. Para ejecutar múltiples sentencias dentro de un bucle, utilice una sentencia block ({ ... }) para agrupar dichas sentencias.

[editar] Descripción

A for...in loop does not iterate over built-in properties. These include all built-in methods of objects, such as String's indexOf method or Object's toString method. However, the loop will iterate over all user-defined properties (including any which overwrite built-in properties).

A for...in loop iterates over the properties of an object in an arbitrary order. If a property is modified in one iteration and then visited at a later time, the value exposed by the loop will be its value at that later time. A property which is deleted before it has been visited will not then be visited later. Properties added to the object over which iteration is occurring may either be visited or omitted from iteration. In general it is best not to add, modify, or remove properties from the object during iteration, other than the property currently being visited; there is no guarantee whether or not an added property will be visited, whether a modified property will be visited before or after it is modified, or whether a deleted property will be visited before it is deleted.

Although it may be tempting to use this as a way to iterate over an Array, this is a bad idea. The for...in statement iterates over user-defined properties in addition to the array elements, so if you modify the array's non-integer or non-positive properties (e.g. by adding a "foo" property to it or even by adding a method or property to Array.prototype), the for...in statement will return the name of your user-defined properties in addition to the numeric indexes. Also, because order of iteration is arbitrary, iterating over an array may not visit elements in numeric order. Thus it is better to use a traditional for loop with a numeric index when iterating over arrays.

[editar] Ejemplos

[editar] Ejemplo: Usando for...in

La siguiente función toma como argumentos un objeto y el nombre de un objeto. Entonces itera sobre todas las propiedades del objeto y devuelve una cadena que lista los nombres de las propiedades y sus valores.

function mostrar_propiedades(objeto, nombreObjeto) {
   var resultado = "";
   for (var i in objeto) {
      resultado += nombreObjeto + "." + i + " = " + objeto[i] + "\n";
   }
   return resultado;
}

[editar] Vea También