Read array values in a loop in JavaScript

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

    If you are OK with manipulating your original array as you loop through it you could splice and concat similar to below (or you could use a clone of the array if you need to persist the original array):

    var myStringArray = ["1","2","3","4","5","6","7","8","9","10"];
    
    var loopByX = function(x){
      var y = myStringArray.splice(0,x);
      myStringArray = myStringArray.concat(y);
      
      return y;
    }
    
    console.log(loopByX(3));
    console.log(loopByX(3));
    console.log(loopByX(3));
    console.log(loopByX(3));
    console.log(loopByX(3));

    If you want to go bi-directional (is that what you call it?), as mentioned in the comments, you could do it as below which then gives you the ability to go backwards or forward and the flexibility to do so in an arbitrary number:

    var myStringArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
    
    var loopByX = function(x) {
      var len = myStringArray.length;
    
      // Ensure x is always valid but you can add any behaviour here in that case yourself. As an example I return an empty array.
      if (Math.abs(x) > len) {
        return [];
      }
    
      var y = x > 0 ? myStringArray.splice(0, x) : myStringArray.splice(len + x, len);
    
      myStringArray = x > 0 ? myStringArray.concat(y) : y.concat(myStringArray);
    
      return y;
    }
    
    console.log(loopByX(20)); // invalid number
    console.log(loopByX(-20)); // invalid number
    console.log(loopByX(-3));
    console.log(loopByX(-6));
    console.log(loopByX(3));
    console.log(loopByX(4));

    0 讨论(0)
  • 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());
    // …
    
    0 讨论(0)
提交回复
热议问题