Obtener contador/índice de bucle usando para syntax de sintaxis en JavaScript


Precaución:

Pregunta todavía se aplica a for…of bucles.> No use for…in para iterar sobre una matriz , úselo para iterar sobre las propiedades de un objeto. Dicho esto, este


Entiendo que la sintaxis básica for…in en JavaScript se ve así:

for (var obj in myArray) {
    // ...
}

Pero ¿cómo obtengo el bucle contador/índice?

Sé que probablemente podría hacer algo como:

var i = 0;
for (var obj in myArray) {
    alert(i)
    i++
}

O incluso el bien antiguo:

for (var i = 0; 1 < myArray.length; i++) {
    var obj = myArray[i]
    alert(i)
}

Pero prefiero usar el bucle for-in más simple. Creo que se ven mejor y tienen más sentido.

¿Hay una manera más simple o más elegante?


En Python es fácil:

for i, obj in enumerate(myArray):
    print i
Author: vsync, 2012-04-16

6 answers

for…in itera sobre nombres de propiedades, no valores, y lo hace en un orden no especificado (sí, incluso después de ES6). No debe usarlo para iterar sobre matrices. Para ellos, existe el método forEach de ES5 que pasa tanto el valor como el índice a la función que le das:

var myArray = [123, 15, 187, 32];

myArray.forEach(function (value, i) {
    console.log('%d: %s', i, value);
});

// Outputs:
// 0: 123
// 1: 15
// 2: 187
// 3: 32

O ES6 Array.prototype.entries, que ahora tiene soporte en las versiones actuales del navegador:

for (const [i, value] of myArray.entries()) {
    console.log('%d: %s', i, value);
}

Para iterables en general (donde usarías un bucle for…of en lugar de un for…in), no hay nada incorporado, sin embargo:

function* enumerate(iterable) {
    let i = 0;

    for (const x of iterable) {
        yield [i, x];
        i++;
    }
}

for (const [i, obj] of enumerate(myArray)) {
    console.log(i, obj);
}

Demo

Si realmente quisieras decir for…in – enumerando propiedades – necesitarías un contador adicional. Object.keys(obj).forEach podría funcionar, pero solo incluye propiedades propias; for…in incluye propiedades enumerables en cualquier lugar de la cadena de prototipos.

 250
Author: Ry-,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-02 01:08:20

En ES6, es bueno usar el bucle for - of. Usted puede obtener índice en para de como este

for (let [index, val] of array.entries()) {
        // your code goes here    
}

Tenga en cuenta que Array.entries()devuelve un iterador, que es lo que le permite trabajar en el bucle for-of; no confunda esto con el Objeto .entries () , que devuelve un array de pares clave-valor.

 80
Author: rushUp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-29 16:22:05

Solución para colecciones de matrices pequeñas:

for (var obj in arr) {
    var i = Object.keys(arr).indexOf(obj);
}

Arr - ARRAY, obj - CLAVE del elemento actual, i - CONTADOR / ÍNDICE

Aviso: Method keys() no está disponible para la versión IE Polyfill. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

 16
Author: iwasborntobleed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-14 03:02:31

For-in-loops itera sobre las propiedades de un objeto. No los use para arreglos, incluso si a veces funcionan.

Las propiedades de los objetos entonces no tienen índice, son todas iguales y no se requiere que se ejecuten en un orden determinado. Si desea contar propiedades, tendrá que configurar el contador extra (como hizo en su primer ejemplo).

Bucle sobre una matriz:

var a = [];
for (var i=0; i<a.length; i++) {
    i // is the index
    a[i] // is the item
}

Bucle sobre un objeto:

var o = {};
for (var prop in o) {
    prop // is the property name
    o[prop] // is the property value - the item
}
 12
Author: Bergi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-16 18:55:11

Como otros han dicho, no deberías usar for..in iterar sobre una matriz.

for ( var i = 0, len = myArray.length; i < len; i++ ) { ... }

Si quieres una sintaxis más limpia, puedes usar forEach:

myArray.forEach( function ( val, i ) { ... } );

Si desea utilizar este método, asegúrese de incluir el shim ES5 para agregar soporte para navegadores más antiguos.

 5
Author: Robert Messerle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-16 18:55:37

¿Qué tal esto

let numbers = [1,2,3,4,5]
numbers.forEach((number, index) => console.log(`${index}:${number}`))

Donde array.forEach el método tiene un parámetro index que es el índice del elemento actual que se está procesando en la matriz.

 4
Author: Sanjay Shr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-13 09:16:04