Search code examples
javascriptarrayscycle

Cycle numbers of array with JavaScript


I'm trying to cycle an array similar to this with JavaScript. arr0=[0,1,2,3] I want to cycle the last number in the array to the first index and continue to cycle through the array numbers. I tried to use an interval and shift push and pop but I can't make the array cycle.

outArr0 = [0, 1, 2, 3];
var cou0 = -1;
var int0 = setInterval(function() {
  cou0++

  var pushThis0 = outArr0[outArr0.length - 1];
  outArr0.pop();
  outArr0.shift();
  outArr0[0] = pushThis0;
  console.log(outArr0);

  if (cou0 == 6) {
    clearInterval(int0)
  }
}, 500);


Solution

  • Please check following code, just fixed your codes,

    outArr0 = [0, 1, 2, 3];
    var cou0 = -1;
    var int0 = setInterval(function() {
      cou0++
      console.log(outArr0[0]);
      outArr0.push(outArr0.shift());
      //
    
      if (cou0 == 6) {
        clearInterval(int0)
      }
    }, 500);