开发者

Javascript - assigning dynamic values without eval()

So, I have 3 variables being passed in:

  1. stats (JSON object, shown below)
  2. place_type (string, either "US" or "State")
  3. factor (string)
开发者_JS百科

I have another variable, answer, whose value depends on the other variables. For example, if place_type = "State" and factor = "factor2", then

var answer = stats.State.factor2; // equals "E"

I'm trying to see if there's a way to dynamically assign a variable without needing to use eval().

// Simplified, there are many more than 3 factors
var stats = {
    "US": {
        "factor1" : "A",
        "factor2" : "B",
        "factor3" : "C"
    },
    "State": {
        "factor1" : "D",
        "factor2" : "E",
        "factor3" : "F"
    }
}

Using eval(), this is how it's done:

eval("var answer = stats." + place_type + "." + factor + ";");

Is this possible in JS without needing eval() or a ton of different IF loops? Thanks in advance.


Here you go:

var answer = stats[place_type][factor];

Live demo: http://jsfiddle.net/simevidas/NsT8Y/


Consider putting this in a try-catch block since you chain property accessors. If the place_type property does not exist in stats, then stats[place_type] will return undefined, and undefined[factor] will throw an error.

var answer;

try { 
    answer = stats[place_type][factor];
} catch(e) {}


For this example, it's easy. The equivalent syntax to

var answer = stats.State.factor2;

is

var answer = stats["State"]["factor2"];

and the latter syntax will work with a variable in place:

var answer = stats[place_type][factor];


var answer = stats[place_type][factor];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜