使用动态变量作为多维对象的键

时间:2012-07-19 05:05:28

标签: javascript

我已经疯狂地击中了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;

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

2 个答案:

答案 0 :(得分: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]; 

除非您想要构建全局变量but normally, local variables suffize

,否则始终将var加到变量前面

答案 1 :(得分: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];