我已经疯狂地在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;
这段代码会检查状态数组(state array),查找其自身数组的“NV”数组,最终查找对应状态的变量,然后引用与该状态相关的颜色。在这种情况下,关闭状态将返回"#FF0000"。
如果我按照上述方法编写代码,则会返回“未定义”的错误。但是,如果我像这样编写代码:
currentColor = state['NV'].status;
它现在运行得非常完美。但这违背了初衷,因为它变成了静态的。我需要保持stateCode动态化,因为它基于一个函数的反馈,而且会不断地变化。
我可以像这样做:
if(stateCode === 'NV') currentColor = state['NV'].status;
if(stateCode === 'WY') currentColor = state['WY'].status;
但是它很快就会变得臃肿。必须有更好的方法来处理这个问题。有什么想法吗?