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?
Keith Rousseau
4,4931 gold badge24 silver badges28 bronze badges
asked Feb 6, 2010 at 3:52
mike
1,5363 gold badges17 silver badges25 bronze badges
3 Answers 3
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;
answered Feb 6, 2010 at 4:14
outis
77.7k23 gold badges155 silver badges228 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
mike
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 =/ ?
outis
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.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.
answered Feb 6, 2010 at 4:12
Jonathon Faust
12.6k4 gold badges53 silver badges63 bronze badges
Comments
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"
answered Feb 6, 2010 at 4:13
scunliffe
63.8k26 gold badges133 silver badges168 bronze badges
3 Comments
mike
Actually, I modified this into this: var key = BodyWeight[i]['ExerciseTitle']; window[key] = BodyWeight[i]["ExerciseVideo"]; And it worked! So thanks!
outis
Except that globals are evil (c2.com/cgi/wiki?GlobalVariablesAreBad, 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.
scunliffe
@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.
lang-js
windowin web browsers, but not necessarily elsewhere. Local variables aren't properties.