/    Sign up×
Community /Pin to ProfileBookmark

Dynamic Variable Concatenation

Hey, I’ve been working on a script for a few hours here that’s just got me bugged!

I have several variables in a file called statelist.js which is linked at the top of my file:

[code=html]
var state1 = “alabama”;
var state2 = “alaska”;
var state3 = “arizona”;
[/code]

then, on my main page I am trying to concatenate the word “state” with a looping number in a while statement:

[code=html]
var c = 1;
while(c <= 3) {
var getState = “state”+c;
alert(getState);
c++
}
[/code]

Of course, with the quotes around it Alert just prints “state1” but without the quote it tells me state is undefined, but of course, I don’t want state, I want state1, state2, etc. which are defined.

Does anyone know what I need to do to concatenate the word state with the looping variable “c” to produce “Alabama” when alerted?

Thanks!!

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@sneakyimpMar 06.2008 — You should create either an array or object to store the state values:
[code=php]
var state = new Array();
state[0] = 'alabama';
state[1] = 'alaska';
state[2] = 'arkansas';
[/code]


then you can loop like this:
[code=php]
for(i=0; i<state.length; i++) {
alert(state[i]);
}
[/code]
Copy linkTweet thisAlerts:
@ts10authorMar 06.2008 — Oh yeah! I knew I was missing something. I've had a migraine all day and I knew I wasn't thinking straight.
×

Success!

Help @ts10 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...