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

Using dynamic variable as key with multidimensional object

本文关键字:对象 动态 变量      更新时间:2023-11-13

我在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;

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

顺便说一下,您正在构建的是Objects而不是Arrays

如果你想保持代码的动态性,请保留一个颜色对象:

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

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

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

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

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

除非您想构造全局变量,否则始终在变量前面加上var的前缀,但通常情况下,局部变量的后缀为

此结构不是数组,而是对象初始值设定项。不管怎样,你需要这样的东西:

var colorCodes = {
    endangered: '#FFA500',
    shutdown: '#FF0000',
    active: '#00BB00'
};
var state = {
    // What you have there
};
var stateCode = '[State Code]';
var currentColor = colorCodes[state[stateCode].status];