Read array values in a loop in JavaScript

  • A+

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

var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; 

And when I call a function the first time function, I need to get this:

1 2 3 

Calling it again I need to get:

4 5 6 

Calling it again:

7 8 9 

Calling it again:

10 1 2 

Calling again:

3 4 5 

And so on. You got the point, showing 3 values from the array and if we are at the end of array, read from the beginning... I have an app that has remote control and has down and up keys. When the user presses the down button to get these values from an array as described in the above example, if the user presses the up button it needs to go back from an reading the array in a loop (at end, the array is read from the beginning, but always shows three values).

I try using this:

var myStringArray = ["1","2","3","4","5","6","7","8","9","10"]; var arrayLength = myStringArray.length; for (var i = 0; i < arrayLength; i++) {     if (i<(6)) {        console.log(myStringArray[i]);     } } 

But the next time I call this code, it shows from the beginning values of the array, not continue to read others I need a second counter?

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));


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: