simple javascript question

debaser_

Limp Gawd
Joined
Apr 1, 2005
Messages
176
Can you declare a variable and have the name be a concatenation? Similar to this...

var 'total'+ product = product * number;
 
You'd have to use array/object notation.

var foo=new Array();
foo['total' + product] = product * number;

or, if you are okay with having global variables.

window['total' + product] = product * number;

most often though, you'd just use an array...

total=new Array();
total[product] = product * number;
 
Thanks, but the catch is that the problem asks that I dont use arrays. This is a class I took as an elective for the hell of it, didnt buy the book, and now wanna get over with...

I guess i cant do it the way i had thought, so it will have to be much sloppier :p
 
eval("var total" . product . "=" . (product*number));

eval() puts into JS code the string you pass it (meaning it interprets the string as if it were actual code).
 
Just don't ever use eval like that in actual practice. Eval is the javascript equivilent of goto - occasionally needed, but generally disliked due to how easy it is to abuse it and produce slow ugly code.
 
Back
Top