2016-02-26 80 views
0

我製作了一個查找表,其中的鍵是用戶名單的名稱。我已經將每個列表的值存儲在一個函數中,並且難以獲取值。如何在列表鍵中獲得特定值?從JavaScript查找表中獲取價值

的jsfiddle:https://jsfiddle.net/pgpx28r9/

我試圖:

var listLookupTable = { 
    '1': function(){ 
     return { 
     'comments': 'a comment', 
     isPrivate:true, 
     revealAmazingStuff:false, 
     receiveFreeStuff:false, 
     receiveEmails:true, 
     } 
    }, 
    'two': function(){ 
    return { 
     comments: 'cool', 
     isPrivate:false, 
     revealAmazingStuff:false, 
     receiveFreeStuff:true, 
     receiveEmails:true, 
     } 
    }, 
    'new stuff': function(){ 
     return { 
     comments: 'another one', 
     isPrivate:true, 
     revealAmazingStuff:true, 
     receiveFreeStuff:true, 
     receiveEmails:true, 
     } 
    }, 
} 

console.log(listLookupTable['1']); 

回答

2

您正在訪問/恢復功能。爲了得到這些值,你必須先調用的函數,然後使用property accessor,像

listLookupTable['1']().comments 
// function call ^^ 
//     ^^^^^^^^^ property accessor 

listLookupTable['1']()['comments'] 
// function call ^^ 
//     ^^^^^^^^^^^^ property accessor 

對於版本魔女返回一個功能,我建議存儲功能的結果撥打一個變量,因爲你只需要一個電話用於獲取對象:

one = listLookupTable['1'](); 
alert(one.comment + one.isPrivate); 

如果你不喜歡的函數調用,或沒有活動的內容,你可以使用一個對象文字與對象而不是函數中:

var listLookupTable = { 
 
    '1': { 
 
     'comments': 'a comment', 
 
     isPrivate: true, 
 
     revealAmazingStuff: false, 
 
     receiveFreeStuff: false, 
 
     receiveEmails: true, 
 
    }, 
 
    'two': { 
 
     comments: 'cool', 
 
     isPrivate: false, 
 
     revealAmazingStuff: false, 
 
     receiveFreeStuff: true, 
 
     receiveEmails: true, 
 
    }, 
 
    'new stuff': { 
 
     comments: 'another one', 
 
     isPrivate: true, 
 
     revealAmazingStuff: true, 
 
     receiveFreeStuff: true, 
 
     receiveEmails: true, 
 
    }, 
 
}; 
 

 
document.write(listLookupTable['1'].comments);