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;

但它很快就变得臃肿。必须有更好的方法来处理这个问题。有任何想法吗?

4

2 回答 2

2

顺便说一句,你正在构建的是Objects而不是Arrays

如果要保持代码动态,请保留一个颜色对象:

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

然后使用字符串来指示状态,而不是状态对象上的变量:

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

并像这样评估您当前的颜色:

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

var除非你想构造一个全局变量,否则总是给你的变量添加前缀,但通常,局部变量就足够了

于 2012-07-19T05:22:14.943 回答
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];
于 2012-07-19T05:18:48.037 回答