JavaScript: cycle through an array (rather than pop)? - Stack Overflow

admin2025-04-19  1

I'm creating map markers, and I want to assign a different colour to each county on the map.

I don't know in advance how many counties there will be showing on the map, so I need to figure out a way to assign an unlimited number of colours.

At the moment, I'm assigning a colour to each county using the following code, but I run into a problem when I pop() the list too many times:

var colours = ['6183A6', '3A66A7', '3B4990', '5B59BA'];
var h_colours = []; // associative array 
function addMarker(county, colour) {
if (colour==undefined) {
    if (h_colours[hundred]==undefined) {
            h_colours[hundred] = colours.pop();
    } } }

Is there a way I could cycle through the list without actually deleting items, and continuing from the start of the list when I reach the end?

thanks!

I'm creating map markers, and I want to assign a different colour to each county on the map.

I don't know in advance how many counties there will be showing on the map, so I need to figure out a way to assign an unlimited number of colours.

At the moment, I'm assigning a colour to each county using the following code, but I run into a problem when I pop() the list too many times:

var colours = ['6183A6', '3A66A7', '3B4990', '5B59BA'];
var h_colours = []; // associative array 
function addMarker(county, colour) {
if (colour==undefined) {
    if (h_colours[hundred]==undefined) {
            h_colours[hundred] = colours.pop();
    } } }

Is there a way I could cycle through the list without actually deleting items, and continuing from the start of the list when I reach the end?

thanks!

Share Improve this question asked Dec 29, 2010 at 20:36 AP257AP257 94.2k89 gold badges207 silver badges263 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

Yes.

 var getNextColour = (function() {
   var colours = ['6183A6', '3A66A7', '3B4990', '5B59BA'];
   var cc = 0;
   return function() {
     var rv = colours[cc];
     cc = (cc + 1) % colours.length;
     return rv;
   };
 })();

Now you can just say:

 if (colour == undefined) colour = getNextColour();

or simply

 colour = colour || getNextColour();

Of course, applying the colors to the elements of the map such that you don't color adjacent areas with the same color is a considerably more interesting problem.

You can use a counter for the index in the array.

Increment whenever you fetch a color, reset it to 0 when it is the size of the array -1.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745002489a279314.html

最新回复(0)