Get loop counter/index using for…of syntax in JavaScript

后端 未结 11 1926
走了就别回头了
走了就别回头了 2020-11-28 00:55

Caution:

question still applies to for…of loops.> Don\'t use for…in to iterate over an Array, use it

相关标签:
11条回答
  • 2020-11-28 01:27

    As others have said, you shouldn't be using for..in to iterate over an array.

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

    If you want cleaner syntax, you could use forEach:

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

    If you want to use this method, make sure that you include the ES5 shim to add support for older browsers.

    0 讨论(0)
  • 2020-11-28 01:27

    To use for..of loop on array and retrieve index you can you use array1.indexOf(element) which will return the index value of an element in the loop. You can return both the index and the value using this method.

    array1 = ['a', 'b', 'c']
    for (element of array1) {
        console.log(array1.indexOf(element), element) // 0 a 1 b 2 c
    }

    0 讨论(0)
  • 2020-11-28 01:29

    For-in-loops iterate over properties of an Object. Don't use them for Arrays, even if they sometimes work.

    Object properties then have no index, they are all equal and not required to be run through in a determined order. If you want to count properties, you will have to set up the extra counter (as you did in your first example).

    loop over an Array:

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

    loop over an Object:

    var o = {};
    for (var prop in o) {
        prop // is the property name
        o[prop] // is the property value - the item
    }
    
    0 讨论(0)
  • 2020-11-28 01:30

    for…in iterates over property names, not values, and does so in an unspecified order (yes, even after ES6). You shouldn’t use it to iterate over arrays. For them, there’s ES5’s forEach method that passes both the value and the index to the function you give it:

    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
    

    Or ES6’s Array.prototype.entries, which now has support across current browser versions:

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

    For iterables in general (where you would use a for…of loop rather than a for…in), there’s nothing built-in, however:

    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

    If you actually did mean for…in – enumerating properties – you would need an additional counter. Object.keys(obj).forEach could work, but it only includes own properties; for…in includes enumerable properties anywhere on the prototype chain.

    0 讨论(0)
  • 2020-11-28 01:37

    Solution for small array collections:

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

    arr - ARRAY, obj - KEY of current element, i - COUNTER/INDEX

    Notice: Method keys() is not available for IE version <9, you should use Polyfill code. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

    0 讨论(0)
提交回复
热议问题