2015-02-23 126 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

相關問題