簡體   English   中英

從JavaScript查找表中獲取價值

[英]Getting value out of JavaScript lookup table

我做了一個查找表,其鍵是用戶創建的列表的名稱。 我已經將每個列表的值存儲在函數中,並且很難獲取這些值。 如何在列表鍵中獲取某個值?

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']);

您正在訪問/返回功能。 為了獲取值,您必須先調用該函數,然后使用屬性訪問器 ,例如

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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM