我已经疯狂地点击 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;
但它很快就变得臃肿。必须有更好的方法来处理这个问题。有任何想法吗?