Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Jackie Jen
2,723 Pointshow to combine variable in javascript
let said i want the javascript variable of 'var ru' and the symbol u is a number that keep increasing. therefore i do not want to manually insert var ru;
but in javascript i wrote the code var ("r" + "u")=100; document.getElementById("demo").innerHTML =ru;
but did not show any thing
3 Answers
Michael Hulet
47,913 PointsThis StackOverflow thread gives you a few good ways to do this
romanok
4,556 PointsNot sure if that's what you mean, but anyway:
if you want to combine 2 number variables into a string, you can use .toString() method.
So if you have
var r = 10
and
var u = 0
you can do:
var ru = r.toString() + u.toString()
ru will be '100'
There's also .parseInt() method to convert strings to numbers
Stone Preston
42,016 Pointsi think what hes after is a way to dynamically generate a variable name maybe?. some languages let you do that sort of thing. dont know if its possible in javascript.
Jackie Jen
2,723 PointsIf let said I would like to have var r1 var r2 var r3 var r4 var r5
But i dun want manually write those 5 variable. i would like to use for loop for (y=1; y<6; y++){ var ("r"+y); }
am i doing the right things?
Tech Solutions
6,077 Pointsso you want the variable r to remain static but the variable u to be dynamic?
var r = 1;
var u = function u(){
for(var i = 0; i > 5; i++;)
});
var ru = r + u;
Roman Kuzhelev
7,853 PointsRoman Kuzhelev
7,853 PointsKenny,
regarding the specific case you've mentioned (and not a problem of dynamic variable's name generation) - why would not consider just to use an array instead?