By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,143 Members | 855 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,143 IT Pros & Developers. It's quick & easy.

Javascript string to variable

CroCrew
Expert 100+
P: 563
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
Share this Question
Share on Google+
4 Replies


gits
Expert Mod 5K+
P: 5,333
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
Expert 100+
P: 563
Can I also set a new value to the variable using..

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


Thanks~
Jan 24 '08 #3

CroCrew
Expert 100+
P: 563
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
Expert Mod 5K+
P: 5,333
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.