2012-07-19 62 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]; 
相关问题