我有一个如下所示的数组
var colorArray = ["#a", "#b", "#c", "#d", "#e"];
从这里我将生成这样的地图
function initilizeColorMap(){
for(var i = 0 ;i <colorArray.length ;i++){
colorTrackingMap[i] = {value: colorArray [i],state:"unused"};
}
}
当我需要一种颜色(地图中的下一种颜色)时,通过检查javascript中的状态,我可以遍历地图。?
答案 0 :(得分:1)
您可以使用一种方法返回下一种颜色。看看这个jsfiddle:http://jsfiddle.net/QYWDb/
var colorArray = ["#a", "#b", "#c", "#d", "#e"];
var colorTrackingMap = [];
var currentIndex = -1;
for(var i = 0 ;i <colorArray.length ;i++){
colorTrackingMap[i] = {value: colorArray [i],state:"unused"};
}
function getNextColor() {
if (currentIndex > colorTrackingMap.length)
currentIndex = 0;
else
currentIndex++;
while ( colorTrackingMap[currentIndex] !== undefined &&
colorTrackingMap[currentIndex].state !== "unused" ) {
currentIndex++;
}
if ( colorTrackingMap[currentIndex] )
return colorTrackingMap[currentIndex].value;
else
return "No color available";
}
答案 1 :(得分:0)
如果根据给定的索引需要颜色,则无需迭代,请使用以下代码:
var currentIndex = 0;
function Next() {
var tracking = colorTrackingMap[currentIndex];
alert("color: " + tracking.value + ", state: " + tracking.state);
currentIndex++;
if (currentIndex >= colorTrackingMap.length)
currentIndex = 0;
}
如果您的意思是在数组中搜索具有特定值的项目,只需使用普通循环:
function Find() {
var color = document.getElementById("color").value;
var state = "";
for (var i = 0; i < colorTrackingMap.length; i++) {
if (colorTrackingMap[i].value.toLowerCase() === color) {
state = colorTrackingMap[i].state;
break;
}
}
if (state.length == 0) {
alert("color isn't mapped");
} else {
alert("state: " + state);
}
}
您也可以将颜色作为函数参数传递,这只是为了举例。
答案 2 :(得分:0)
您可以使用以下内容:
var ColourMap = function (arr) {
var _map = [],
out = [],
i,
len;
// Set up the colour map straight away
for (i = 0, len = arr.length; i < len; i++) {
_map.push({
value: arr[i],
state: "unused"
});
}
return {
get_next: function () {
var i,
len,
next;
for (i = 0, len = _map.length; i < len; i++) {
if (_map[i].state === "unused") {
next = _map[i];
break;
}
}
return next;
}
}
};
然后使用类似的东西:
var m = new ColourMap(["#a", "#b", "#c", "#d", "#e"]);
m.get_next(); // get the next available element