简体   繁体   中英

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). 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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