Read array values in a loop in JavaScript

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

    How about using a generator:

    function* get3() {
      var myStringArray = ["1","2","3","4","5","6","7","8","9","10"];
      var index = 0;
      while (true) {
        yield [0, 1, 2].map(i => myStringArray[(index + i) % myStringArray.length])
        index = (index + 3) % myStringArray.length;
      }
    }
    

    Calling this function returns an object which you can call .next() on, to get the next set of 3:

    var getter = get3();
    console.log(getter.next().value); // ["1","2","3"]
    console.log(getter.next().value); // ["4","5","6"]
    console.log(getter.next().value); // ["7","8","9"]
    // etc.
    

提交回复
热议问题