Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to loop through array items multiple times

So, if I wanted to log the numbers one to five once, I might write something like:

var array = [1,2,3,4,5]

function loop(n) {
  for (var i=0;i<n;i++) {
    console.log(array[i])
  }
}

loop(5)

but how would I log the numbers one to five more than once?

eg writing loop(10); to get the following result: 1 2 3 4 5 1 2 3 4 5

Obviously at the moment I get 'undefined' for anything above loop(5)

like image 423
Hello World Avatar asked Nov 04 '13 17:11

Hello World


1 Answers

Use the remainder operator :

function loop(n) {
  for (var i=0;i<n;i++) {
    console.log(array[i%array.length])
  }
}
like image 87
Denys Séguret Avatar answered Sep 22 '22 07:09

Denys Séguret