views:

288

answers:

3

I want to get a value from a variable then use that as the name for another variable. I got something like this:

var eval(BodyWeight[i]["ExerciseTitle"]) = BodyWeight[i]["ExerciseVideo"]; 

This is giving me an error, 'missing ; before statement'.

Any ideas?

+1  A: 

It will be easier if you specify the part you currently have enclosed in eval as a property.

var myvar = {};
myvar[BodyWeight[i]["ExerciseTitle"]] = BodyWeight[i]["ExerciseVideo"];

No evil eval necessary.

Jonathon
A: 

If I understand what you are hoping to accomplish:

var eval(BodyWeight[i]["ExerciseTitle"]) = BodyWeight[i]["ExerciseVideo"]; 

//to try and get
var BodyWeight4ExerciseTitle = BodyWeight[i]["ExerciseVideo"];
              ^-//guessing this is an iterator

To accomplish this, just do:

var key = 'BodyWeight' + i + 'ExerciseTitle';
window[key] = BodyWeight[i]["ExerciseVideo"];

//now you have a global variable "BodyWeight4ExerciseTitle"
scunliffe
Actually, I modified this into this:var key = BodyWeight[i]['ExerciseTitle'];window[key] = BodyWeight[i]["ExerciseVideo"];And it worked! So thanks!
mike
Except that globals are evil (http://c2.com/cgi/wiki?GlobalVariablesAreBad, http://www.google.com/search?q=globals+are+evil). Unless you have a compelling reason to use globals (which I don't see for this problem), use local variables or object properties instead.
outis
@outis - true... I wasn't sure how the OP needed this variable so sticking it in the window was a simple option... but it could just have easily been stuck in another object.
scunliffe
+1  A: 

While eval will give you a form of variable variables, it's messy and potentially leads to syntax errors:

try {
    eval('var ' + BodyWeight[i]["ExerciseTitle"] + ' = BodyWeight[i].ExerciseVideo');
} catch () {
    // what to do here if BodyWeight[i]["ExerciseTitle"] isn't a valid variabe name?
}

Better to use object properties rather than local variables.

thing[BodyWeight[i].ExerciseTitle] = BodyWeight[i].ExerciseVideo;
outis
This is what I got so far: eval('var ' + BodyWeight[i]["ExerciseTitle"] + ' = ' + BodyWeight[i]["ExerciseVideo"]);Except it's giving me an error 'unexpected end of XML entity'. Any ideas =/ ?
mike
That's basically the syntax problem I mentioned. The difference between your code and mine is significant. In this case, `eval` leads you down a dark path. Use object properties instead.
outis