I’m playing around with building a little Texas Hold ‘em simulator. I set up the players as an array, and started a hand. I realized pretty quickly that I’ll need to start play at a different player each hand, which means looping over the array with a different offset every time. I wondered, how do I loop over the entire array, beginning at a position other than 0? And then the magical modulus operator came to my rescue.
12345678910111213141516
// set up the arrayvarfruit=['banana','apple','orange','kiwi','watermelon'];// set an offsetvaroffset=3;// loop over the arrayfor(vari=0;i<fruit.length;i++){// calculate the iteratorvarit=(i+offset)%fruit.length;// access the array element, using the fancy iteratorconsole.log(fruit[it]);}