从JavaScript查找表中获取价值

时间:2016-02-26 09:26:47

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

1 个答案:

答案 0 :(得分: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);