Read array values in a loop in JavaScript

前端 未结 8 2032
执笔经年
执笔经年 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:07

    If you want the immutable way to achieve your circular looping

    function loopArray(arr, step=3) {
        let i = 0;
        return function inner() {
            for (let j = 0; j < step; j++) {
                console.log(arr[i]);
                i = (i + 1) % arr.length;
            }
        };
     }
    
    const func = loopArray(["1","2","3","4","5","6","7","8","9","10"], 3);
    func();
    func();
    func();
    func();
    func();
    

提交回复
热议问题