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

后端 未结 11 1960
走了就别回头了
走了就别回头了 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:22

    Here's a function eachWithIndex that works with anything iterable.

    You could also write a similar function eachWithKey that works with objets using for...in.

    // example generator (returns an iterator that can only be iterated once)
    function* eachFromTo(start, end) { for (let i = start; i <= end; i++) yield i }
    
    // convers an iterable to an array (potential infinite loop)
    function eachToArray(iterable) {
        const result = []
        for (const val of iterable) result.push(val)
        return result
    }
    
    // yields every value and index of an iterable (array, generator, ...)
    function* eachWithIndex(iterable) {
        const shared = new Array(2)
        shared[1] = 0
        for (shared[0] of iterable) {
            yield shared
            shared[1]++
        }
    }
    
    console.log('iterate values and indexes from a generator')
    for (const [val, i] of eachWithIndex(eachFromTo(10, 13))) console.log(val, i)
    
    console.log('create an array')
    const anArray = eachToArray(eachFromTo(10, 13))
    console.log(anArray)
    
    console.log('iterate values and indexes from an array')
    for (const [val, i] of eachWithIndex(anArray)) console.log(val, i)
    

    The good thing with generators is that they are lazy and can take another generator's result as an argument.

提交回复
热议问题