tags:

views:

55

answers:

4

I think it's fairly clear what I want to do here:

var viewnames = {};
viewnames['region-a'] = "Region A";
viewnames['region-b'] = "Region B, partial";
viewnames['region-c'] = "Region C";

function loadView(view_name) {
    alert('view_name: ' + view_name);
    alert('viewname: ' + viewnames.view_name);
    document.getElementById("viewtitle").innerText = view_name;
}

But if I call this with view_name as region-a the alert says viewnames.view_name is undefined. What is the problem?

+8  A: 

You must use viewnames[view_name] inside your function loadView

Mic
Thanks! I will accept this answer when the 10 mins are up :)
AP257
To clarify: you can't use a variable for dot accessor syntax; you have to use braces. Thus, `viewnames[view_name]` instead of `viewnames.view_name`.
mway
+1  A: 

You need to index it by name, e.g. viewnames[view_name]

zincorp
A: 

Access it by associative array index (viewnames[view_name]). Please DO NOT use an eval construct (eval("var tmp = viewnames." + view_name + ";")).

palswim
A: 

I upvoted @Mic's answer, but as an alternative -- if you want to use the object.property notation as you have it, you would need to declare it in the following manner:

var viewnames = new function() {
    this.regionA = "Region A"; 
    this.regionB = "Region B, partial"; 
}; 

viewnames.regionC = "Region C"; 

This works, but it's not terribly recommended. Use the other answer as the preferred method.

Joel Etherton
@Downvoter - seriously? a downvote simply for providing a little more information on the notation? If you felt compelled to downvote, by all means, please feel compelled to comment as to why.
Joel Etherton