我有一堆数组属性的自定义对象。如何将JavaScript字符串转换为引用对象属性?
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