2011-12-20 242 views
0

我有一個像下面如何檢查對象屬性在JavaScript

var colorArray = ["#a", "#b", "#c", "#d", "#e"]; 

從這個我會生成一個地圖這樣

function initilizeColorMap(){ 
    for(var i = 0 ;i <colorArray.length ;i++){ 
    colorTrackingMap[i] = {value: colorArray [i],state:"unused"}; 
    } 
} 

Hopw我可以通過地圖迭代當我需要一個數組通過檢查javascript中的狀態來顯示顏色(來自地圖的下一個顏色)。?

+0

我不知道你要完成什麼。您正在爲'colorTrackingMap'的每個元素添加'colorArray [0]'(相同的第一種顏色)。 – pimvdb 2011-12-20 13:37:43

+0

對不起..typo錯誤 – user882196 2011-12-20 13:38:18

回答

0

如果你根據你不必重複給定的索引需要的顏色,使用這樣的代碼:

var currentIndex = 0; 
function Next() { 
    var tracking = colorTrackingMap[currentIndex]; 
    alert("color: " + tracking.value + ", state: " + tracking.state); 
    currentIndex++; 
    if (currentIndex >= colorTrackingMap.length) 
     currentIndex = 0; 
} 

Live test case

如果你的意思是搜索與特定值項的數組,只需使用普通的循環:

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); 
    } 
} 

您也可以通過顏色作爲函數的參數,這僅僅是了一個例子。

Updated test case

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"; 
} 
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 

這裏有一個working example