【发布时间】:2015-04-24 22:13:24
【问题描述】:
我有一个带有一堆数组属性的自定义对象。
function Location (name, displayName){
this.name = name,
this.displayName = displayName,
Location.objects.push(this);
}
Location.objects = [];
//Initialize Farm
var farm = new Location();
farm.scenes = [
"content 0",
"content 1",
"Content 2"
];
使用 JQuery,我从 DOM 中获取一个属性,我需要使用该属性从对象中调用值。
$('button').click(function(){
var location = $(this).attr('id'); //in this case, the id is 'farm'
mainLoop(location);
});
function mainLoop(location){
console.log(farm.scenes.length);// returns '3' as desired
console.log(location.scenes.length);//returns undefined because location is a string. I need this to work.
console.log(location[scenes][length]); //same problem
}
到目前为止,我发现的唯一解决方案是使用 eval(),但我不能这样做,因为最终用户可能会操纵这些数据。
function mainLoop(location){
location = eval(location);
console.log(location.scenes.length);//returns 3 as desired
}
我需要一种替代方法来获取此字符串并将其转换为对象属性引用。在这种情况下,我处理的结果数量有限,因此我可能会将一组字符串映射到标识符,但我觉得可能有一个更优雅的解决方案,尽管我不知道我应该问什么问题正在输入stackoverflow。
有一个类似的问题Dynamically access object property using variable,但这不适用于此处 - 以下两行使用两种表示法都将解析“3”。我认为我的语法在符号上是正确的,所以我一定是做错了其他事情。
console.log(location.scenes.length); //returns undefined because location is a string. I need this to work.
console.log(location[scenes][length]); //same problem
【问题讨论】:
标签: javascript string object properties eval