2015-02-23 123 views
-2

我有一堆数组属性的自定义对象。如何将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 

回答

0

由于使用location = eval(location);转换成你想要的对象,我认为location在传递给你的mainLoop函数只是表示对象的JSON字符串,相当于'{"scenes" : ["content 0", "content 1", "Content 2"]}'

你可以做什么使用JSON.parse - 在这种情况下:

console.log(location); 
// outputs '{"scenes" : ["content 0", "content 1", "Content 2"]}' 
location = JSON.parse(location); 
console.log(location.scenes.length); // outputs 3 

如今,它在浏览器中非常标准。在this related SO question中有更多关于JSON.parse的信息,它指出如果你已经使用jQuery(它看起来就像你),那么你可以使用$.parseJSON,它可以处理旧版浏览器,回退到eval

相关问题