7

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)

asked Nov 4, 2013 at 17:18
0

1 Answer 1

22

Use the remainder operator :

function loop(n) {
 for (var i=0;i<n;i++) {
 console.log(array[i%array.length])
 }
}
answered Nov 4, 2013 at 17:19

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.