我已经走了屁股打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;
但它会很快变得臃肿。必须有更好的方法来处理这个问题。有任何想法吗?
请注明正是你的“它不能说‘不确定’”是什么意思这是一个控制台错误消息?如果是这样,请显示整个消息。 – HBP 2012-07-19 05:26:13
找出原因(但不是解决方案)。这是一个可变范围的问题。 JSFiddle:http://jsfiddle.net/n7hTw/1/演示了这个问题。当它不是时,它应该提醒状态。 – 2012-07-19 09:30:42