如何使用包含下划线的变量访问对象属性

时间:2016-05-30 10:55:32

标签: javascript jquery

我尝试使用包含下划线的变量来访问对象属性,但是它给出错误Uncaught ReferenceError: topic_ is not defined。我确实研究了这个问题的解决方案Dynamically access object property using variable但是它没有用。

var topics_page_no = {
    topic_1: [2,3,4],
    topic_2: [5,6,7]
}

/* Navigate to particular topic's first page based on selection */
$(document).on('click', '.topic-menu-dropdown-item', function(){
    var topic_id = $(this).data('topic-id');
    console.log(topics_page_no.topic_[topic_id][0] + ".html");
});

预期输出: 2.html / 5.html

3 个答案:

答案 0 :(得分:5)

您可以尝试 Bracket notation

 /* Navigate to particular topic's first page based on selection */
$(document).on('click', '.topic-menu-dropdown-item', function () {
    var topic_id = $(this).data('topic-id');
    console.log(topics_page_no["topic_" + [topic_id]][0] + ".html");
});

答案 1 :(得分:3)

您需要使用括号表示法和一个包含完整变量名称的字符串。 topics_page_no.topic_[topic_id]在名为topics_page_no的{​​{1}}上查找属性,然后尝试在上查找匹配topic_的属性。相反,您希望将topic_id"topic_"合并,以形成要在topic_id上查找的属性的完整名称:

所以:

topics_page_no

答案 2 :(得分:0)

您可以使用这样的括号表示法:

/* Navigate to particular topic's first page based on selection */
$(document).on('click', '.topic-menu-dropdown-item', function () {
   var topic_id = $(this).data('topic-id');
   console.log(topics_page_no["topic_" + [topic_id]][0] + ".html");
});