PDA

View Full Version : Hopefully simple Javascript variable calling problem


sairus
06-18-2009, 11:25 AM
Greetings,
I'm brand new to this Javascript shinanigans and I've run into a problem. It's sort of hard to explain, but I'm simpley trying to output the value of a variable. However I am calling that variable by combining a string and the value of another variable.
Here's a basic non-working example:

------
var i = 0;
var print0 = "Hello ";
var print1 = "World";
var print2 = "!!!!!!";

document.writeln("print"+i);
i++;
document.writeln("print"+i);
i++;
document.writeln("print"+i);
------

I'm trying to get the output
Hello World!!!!!!

But I'm obviously getting
print0print1print2

I can do this grand in Actionscript, but I have no idea on how to accomplish this in Javascript, or if it's even possible.

oesxyl
06-18-2009, 11:34 AM
Greetings,
I'm brand new to this Javascript shinanigans and I've run into a problem. It's sort of hard to explain, but I'm simpley trying to output the value of a variable. However I am calling that variable by combining a string and the value of another variable.
Here's a basic non-working example:

------
var i = 0;
var print0 = "Hello ";
var print1 = "World";
var print2 = "!!!!!!";

document.writeln("print"+i);
i++;
document.writeln("print"+i);
i++;
document.writeln("print"+i);
------

I'm trying to get the output
Hello World!!!!!!

But I'm obviously getting
print0print1print2

I can do this grand in Actionscript, but I have no idea on how to accomplish this in Javascript, or if it's even possible.


var i;
toprint = ["Hello ", "World", "!!!!!!"];
for(i=0;i<3;i++){
document.writeln(toprint[i] + ' ');
}


without evaluation "print" is a string. Try this way:

alert(eval("print" + 0));


best regards

sairus
06-18-2009, 12:17 PM
Ah, (eval("print" + 0)) was exactly what I was looking for!
Thanks man, you're a life saver!