JavaScript: cycle through an array (rather than pop)?
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 ther开发者_开发技巧e 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!
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.
精彩评论