我在使用javascript中的变量访问特定对象时遇到了问题。下面是我正在使用的代码:
global_grouplist = getTenantGroupList();
console.log(global_grouplist)
var currentgroup = getSelectedGroupName();
console.log(currentgroup)
console.log(global_grouplist.currentgroup);'global_grouplist‘返回一个很大的对象数组,我想从中获取一个特定值。如果我取currentgroup等于的值,并像这样运行它:
console.log(global_grouplist.actualvalue)它给了我我想要的。然而,当我这样做的时候。
var currentgroup = actualvalue
console.log(global_grouplist.currentgroup)这是getTenantGroupList()函数:
function getTenantGroupList(){
return jQuery.parseJSON($.ajax({
url: 'tenantgrouplist.json',
dataType: 'json',
async: false
}).responseText);
}下面是getSelectedGroupName函数:
function getSelectedGroupName(){
var retval = null;
$('#grouplist li a').each(function(){
if($(this).parent().hasClass('group-selected'))
retval=$(this).html();
});
return retval;
}它不起作用。我是不是遗漏了什么基本的东西?如果您需要更多信息,请让我知道!
发布于 2012-11-07 21:18:15
要以这种方式访问属性,您需要使用数组表示法。试试这个:
var currentgroup = getSelectedGroupName(); // Returns a string like: 'actualvalue';
console.log(global_grouplist[currentgroup])发布于 2012-11-07 21:19:13
使用此行
var currentgroup = actualvalue您正在将actualvalue的当前值提供给currentgroup,并且不要使这两个元素指向同一属性!
如果要将currentgroup用作变量的占位符,则应改为使用以下内容:
var currentgroup = 'actualvalue';
console.log(global_grouplist[currentgroup]);这样,您可以将所需属性的名称作为字符串分配给currentgroup,并使用括号表示法来访问对象的相应属性。
https://stackoverflow.com/questions/13270568
复制相似问题