简体   繁体   中英

Start a for loop on specific index and loop for array length

I'm trying to do a for loop on an array and be able to start that loop on a specific index and loop over the array x amount of times.

const array = ['c','d','e','f','g','a','b','c']

I want to loop 8 indexes starting at any index I wish. Example starting at array[4] (g) would return

'g','a','b','c','c','d','e','f'

This is what I've tried so far

const notes = ['c','d','e','f','g','a','b','c']

var res = []
for (var i = 4; i < notes.length; i++) {
res.push(notes[i])
}

console.log(res)

You can use modulo % operator.

    const getArray = (array, index) => {
      const result = [];
      const length = array.length;
      for (let i = 0; i < length; i++) {
        result.push(array[(index + i) % length]);
      }
      return result;
    };

Simple way.

 var notes = ['c','d','e','f','g','a','b','c']; function looparr(arr, start) { var res = [], start = start || 0; for(var index = start, length=arr.length; index<length; index++) { res.push(arr[index]); index == (arr.length-1) && (index=-1,length=start); } return res; } console.log(looparr(['c','d','e','f','g','a','b','c'], 0)); console.log(looparr(['c','d','e','f','g','a','b','c'], 2)); console.log(looparr(['c','d','e','f','g','a','b','c'], 4)); console.log(looparr(['c','d','e','f','g','a','b','c'])); 

Very simple solution below :) While i < index, remove the first character from the array, store it in a variable and then add it back onto the end of the array.

 let array = ['c','d','e','f','g','a','b','c']; var index = 4; for(var i = 0; i < index; i++) { var letter1 = array.shift(i); // Remove from the start of the array array.push(letter1); // Add the value to the end of the array } console.log(array); 

Enjoy :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM