admin管理员组文章数量:1406328
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 badges2 Answers
Reset to default 9Yes.
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.
本文标签: JavaScript cycle through an array (rather than pop)Stack Overflow
版权声明:本文标题:JavaScript: cycle through an array (rather than pop)? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745002457a2637062.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论