How to iterate over array elements repeatedly

So, if I wanted to write numbers one to five times once, I could 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 can I register numbers from one to five more than once?

for example, a writing cycle (10); to get the following result: 1 2 3 4 5 1 2 3 4 5

Obviously, at the moment I am getting 'undefined' for anything above the loop (5)

+4
source share
1 answer

Use the remainder operator :

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

All Articles