469,645 Members | 1,148 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,645 developers. It's quick & easy.

Javascript string to variable

CroCrew
564 Expert 512MB
Hello Everyone,

First let me say thanks for the help. Now for the question…

What I am trying to do is have a few declared variables where their names share the same common first part and have a unique second part. Then within a function I pass in the second part of the variable’s name and concatenate that with the first part to alert the value of that variable. Below is my code.

Again thanks for your help~


[HTML]<script language="JavaScript">
var LocalOne=’Hello’;
var LocalTwo=’Wow’;
var LocalThree=’Bye’;

function ShowVar(SecondPart)
{
alert(['Local'+SecondPart].value);
}
</script>[/HTML]
Jan 24 '08 #1
4 14779
gits
5,390 Expert Mod 4TB
hi ...

have a look at the following example ... it assumes that the vars are global:

Expand|Select|Wrap|Line Numbers
  1. var LocalOne = 'Hello';
  2. var LocalTwo = 'Wow';
  3. var LocalThree = 'Bye';
  4.  
  5. function ShowVar(SecondPart) {
  6.     alert(window['Local' + SecondPart]);
  7. }
  8.  
  9. ShowVar('One');
kind regards
Jan 24 '08 #2
CroCrew
564 Expert 512MB
Can I also set a new value to the variable using..

window['Local' + SecondPart] = “Cool”;


Thanks~
Jan 24 '08 #3
CroCrew
564 Expert 512MB
Like this?

Expand|Select|Wrap|Line Numbers
  1. <script language="JavaScript">
  2.      var LocalOne=’Hello’;
  3.      var LocalTwo=’Wow’;
  4.      var LocalThree=’Bye’;
  5.  
  6.      function ShowVar(SecondPart)
  7.      {
  8.           alert(window['Local' + SecondPart]);
  9.           window['Local' + SecondPart] = 'Cool';
  10.      }
  11. </script>
  12.  
Jan 24 '08 #4
gits
5,390 Expert Mod 4TB
you answered your question already for yourself :) that works:

Expand|Select|Wrap|Line Numbers
  1. var LocalOne = 'Hello';
  2. var LocalTwo = 'Wow';
  3. var LocalThree = 'Bye';
  4.  
  5. function ShowVar(SecondPart) {
  6.     window['Local' + SecondPart] = 'test';
  7.     alert(window['Local' + SecondPart]);
  8. }
  9.  
  10. ShowVar('One');
  11.  
  12. // to see for sure that it works:
  13. alert(LocalOne);
  14.  
kind regards
Jan 24 '08 #5

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

3 posts views Thread by XenofeX | last post: by
1 post views Thread by Machi | last post: by
8 posts views Thread by Pavils Jurjans | last post: by
6 posts views Thread by John Kotuby | last post: by
2 posts views Thread by Looch | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.