简体   繁体   English

在javascript对象选择器中使用变量

[英]Use variable in javascript object selector

I ran into a problem when dynamically attempting to retrieve an object row based on a variable. 我在动态尝试基于变量检索对象行时遇到了问题。 What would be a good work around to the following situation? 对于以下情况会有什么好处?

function getDetails(id) {
    completeID = "event" + id;
    title = eventDetails.completeID.title;
}

var eventDetails = {
    'event1': {
        'title': 'Lisbon Earthquake',
            'content': "Test Content",
    },
        'event2': {
        'title': 'Falling Stars',
            'content': 'Test Content'
    }
};

Try this in your method - 在你的方法中尝试这个 -

function getDetails(id) {
    completeID = "event" + id;
    title = eventDetails[completeID].title;
}

as an object property can be accessed using a square bracket notation . 可以使用方括号表示法访问对象属性。

On a side note, in your getDetails function you are declaring your variables without the var keyword (unless they are already defined as globals). 另外,在getDetails函数中,您将声明没有var关键字的变量(除非它们已经定义为全局变量)。 This will create them as global variables, and it is considered a very bad practice to use global variables this way. 这会将它们创建为全局变量,以这种方式使用全局变量被认为是一种非常糟糕的做法。 Try to declare them as follows - 尝试将它们声明如下 -

function getDetails(id) {
    var completeID = "event" + id,
        title = eventDetails[completeID].title;

    // do whatever you want with the title
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM