PDA

View Full Version : Does anyone know how to use two variables added together to alter a different variabl


paulstreats
03-14-2003, 01:43 AM
I have put a number next to each line of script with an explanation below to help you understand what i am trying to achieve:=

-1 var a1=1
-2 var a="a"
-3 var b=1
-4 (a+b)++
-5 document.write(a1)

explanation:

-1 define var a1 to be 1
-2 define var a to be letter 'a'
-3 define var b to be number '1'
-4 combine variables 'a' and 'b' together to create 'a1' then increment it
-5 display result on screen

**i'm trying to get 'a1' to have a value of 2 rather than 1 without refering to the variable directly. I've tried this many ways but none seem to work, I keep getting the error message 'cannot assign to variable a1'

I would be grateful for any help as this would solve a few problems i have in some of my scripts. The only solution that i have right now is a great length of IF _ Else statements but a better solution would create faster flexibility.

Tommi
03-14-2003, 01:53 AM
Sorry, I just took a fast look at it and noticed that you try to add a string variable to an integer variable. That doesn't work since variable a's value is "a" - if it had a numerical string value, you could try parseInt(a) to convert it to an integer value which you can operate mathematically

cheesebagpipe
03-14-2003, 01:54 AM
var a1 = 1;
var a = "a";
var b = 1;
window[a+b]++;
document.write(a1);

Where a="a" and b=1, window[a+b] is the same as window["a1"], which is the same as window.a1, which is the same as simply referencing the global a1.

Jason
03-14-2003, 01:56 AM
your var 2 isn't a char its a string if you use double quotes. I don't know if that helps. And so you might try using var a='a' and var b = '1' so that you can concatinate the two characters.


Jason

Tommi
03-14-2003, 01:59 AM
Never noticed, yet, that JavaScript makes a difference between chars and strings. Is that true?

paulstreats
03-14-2003, 02:08 AM
Maybe if i explain a little more.
say i have declared var a1,a2,a3,a4,a5,a6,a7
then b1,b2,b3,b4,b5,b6,b7
etc... etc... for c de f g h i
all of these have a value of one so i var'a' does change to a="b"
I change from a to b etc.. using other numerical variables ie
-var num=1
if num=1
a="a"
if num=2
a="b"
if num=3
a="c"
etc...

all i'm after is changing the variable without referring to it directly and also without having to type hundreds of lines again and again and again..
------------------------------------------
I've just had a crack at a sample using cheesebagpipe's suggestion and it seems to work, thanks for the help, i should be able to put it to many uses:thumbsup:

cheesebagpipe
03-14-2003, 02:18 AM
Glad it helped. JavaScript - unlike more sophisticated languages - is completely dereferenced, so playing with variables - as opposed to their values - requires some trickery. Do a google search on "javascript associative arrays" for more insight.