2016-03-24 74 views
0

我目前正在尝试创建一个函数,该函数给定一个变量的字符串以返回具有相同名称的数组的结果,意图使用它仅返回所需的twitter配置文件。有没有更好的方法来检查数组的名称字符串?

例如,如果变量配置文件等于ManUtd,则返回数组ManUtd及其内容。

数组ManUtd将包含所有在Twitter上玩这个俱乐部的玩家,然后可以用它来返回那些twitter个人资料。

到目前为止,我最初的想法是做一些事情,如:

var ManUtd = [ 
    // array containing all ManUtd twitter players 
] 

function checkTeam(profile){ 
    if (profile == ManUtd){ 
    // use the array ManUtd 
    } else if { 
    // the rest of the possible results 
} 

这是不是很有效,而且似乎相当冗长的解决方案。有没有更好的方法来实现这些结果?

回答

1

请勿调用全局变量,例如ManUtd。相反,使包含键的对象,你想要的值:

var teams = { 
    'ManUtd': [the array you mentioned], 
    'Arsenal': [some other array], 
    //etc 
}; 

然后得到数组是这样的:

function checkTeam(profile){ 
    if (teams[profile]) { 
    return teams[profile]; 
    } 
} 
+0

谢谢,非常有帮助 – user4357505

相关问题