2012-07-19 63 views
3

我已經走了屁股打Stackflow和谷歌試圖找到解決方案,並最終在這個問題後問幾個小時。使用動態變量作爲關鍵與多維對象

這是我的數組:

endangered = '#FFA500'; 
shutdown = '#FF0000'; 
active = '#00BB00'; 

// Build state array 
var state = {}; 
state = { 
     NV: { 
      status: shutdown, 
      name: 'Las Vegas Charter School for the Deaf', 
      SchoolLink: 'http://www.lvcsd.org', 
      SourceLink: 'http://www.lvrj.com/news/charter-school-for-deaf-signs-off-in-bankruptcy-141399423.html', 
      ClosureDate: 'March 5, 2012', 
      Comment: 'Closure due to bankruptcy. State also adopted exclusive mainstreaming approach.' 
     }, 
     WY: { 
      status: shutdown, 
      name: 'Wyoming School for the Deaf', 
      SchoolLink: 'http://www.wyomingdeaf.com/', 
      SourceLink: 'http://trib.com/news/local/article_94be7523-5bc5-5031-97ee-9431a205cfe9.html', 
      ClosureDate: '2000', 
      Comment: 'School replaced by a mainstream school. State also adopted exclusive mainstreaming approach.' 
     } 
} 

訪問它,然後在這一點上會是這樣的:

stateCode = 'NV'; 
currentColor = state[stateCode].status; 

它會檢查狀態陣列,查找了 'NV'數組有自己的數組,然後最後查看狀態,該狀態也有自己的變量,該變量引用與該狀態關聯的顏色。在這種情況下,它將返回'#FF0000'進行關閉。

如果我這樣做的代碼,它會失敗,說'未定義'。如果我這樣做是這樣的:

currentColor = state['NV'].status; 

它然後完美地工作。但是,這變成靜態的,目的就是失敗。我需要能夠保持stateCode的動態,因爲它是基於函數的反饋,並且會一直在改變。

我能做到這一點是這樣的:

if(stateCode === 'NV') currentColor = state['NV'].status; 
if(stateCode === 'WY') currentColor = state['WY'].status; 

但它會很快變得臃腫。必須有更好的方法來處理這個問題。有任何想法嗎?

+0

請註明正是你的「它不能說‘不確定’」是什麼意思這是一個控制檯錯誤消息?如果是這樣,請顯示整個消息。 – HBP 2012-07-19 05:26:13

+0

找出原因(但不是解決方案)。這是一個可變範圍的問題。 JSFiddle:http://jsfiddle.net/n7hTw/1/演示了這個問題。當它不是時,它應該提醒狀態。 – 2012-07-19 09:30:42

回答

2

順便問一下,你正在構建的Objects and not Arrays

如果你想保持代碼的動態,保持顏色對象:

var colors = { 
endangered: '#FFA500', 
shutdown: '#FF0000', 
active: '#00BB00' 
}; 

然後使用字符串表示狀態而不是狀態對象上的變量:

var state = {}; 
state = { 
    NV: { 
     status: 'shutdown', 

和評估你目前的顏色是這樣的:

var currentColor = colors[state[stateCode].status]; 

始終前綴var到你的變量,除非你想構建一個全局變量,but normally, local variables suffize

+0

您有正確的概念,但在函數內部使用變量時,似乎失敗了。我懷疑這是由於範圍的問題,但在我的生活中,我不明白爲什麼,因爲狀態和顏色代碼幾乎在任何功能之外,而且應該是全球性的。工作版本:http://jsfiddle.net/n7hTw/非工作版本:http://doncullen.net/map/tests/index.html(點擊一個狀態並查看控制檯,查看我提到的未定義錯誤發生在197行) – 2012-07-19 08:55:09

+0

197行發生錯誤是由於state ['TX']'返回undefined。你必須定義你想要在你的狀態對象中調用的所有狀態(除非你想動態分配它們,但是你必須這樣做*)。 – 2012-07-19 09:14:29

+0

絕對是一個範圍問題。添加到您的代碼:var testFunc = function(){thestatus = state [stateCode] .status; alert('thestatus ='+ thestatus); }這將無法訪問狀態和顏色變量。 – 2012-07-19 09:19:29

1

這個結構不是一個數組,這是一個對象初始值設定項。反正你需要的東西是這樣的:

var colorCodes = { 
    endangered: '#FFA500', 
    shutdown: '#FF0000', 
    active: '#00BB00' 
}; 

var state = { 
    // What you have there 
}; 

var stateCode = '[State Code]'; 
var currentColor = colorCodes[state[stateCode].status]; 
相關問題