Read array values in a loop in JavaScript

前端 未结 8 2021
执笔经年
执笔经年 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));

提交回复
热议问题