Read array values in a loop in JavaScript

前端 未结 8 2031
执笔经年
执笔经年 2021-02-14 06:49

I have an array in JavaScript that have defined these values:

var myStringArray = [\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\"];
8条回答
  •  独厮守ぢ
    2021-02-14 07:30

    The fancy solution with generator functions:

    function* cycle(arr) {
        let i=0;
        while (true) {
            yield arr[i++];
            i %= arr.length;
        }
    }
    function* chunksOf(n, iterable) {
        let chunk = [];
        for (const x of iterable) {
            chunk.push(x)
            if (chunk.length >= n) {
                yield chunk;
                chunk = [];
            }
        }
        if (chunk.length > 0)
            yield chunk;
    }
    function toFunction(iterator) {
        return () => iterator.next().value;
    }
    var myStringArray = ["1","2","3","4","5","6","7","8","9","10"];
    
    const f = toFunction(chunksOf(3, cycle(myStringArray)));
    console.log(f());
    console.log(f());
    console.log(f());
    // …
    

提交回复
热议问题