/    Sign up×
Community /Pin to ProfileBookmark

HELP!! Script won’t work!!

I’ve been using Javascript for a while and I usually get things done (though, not always in the best way…:-))

I need to create a simple script to run a loop that has to output several strings.

Basically, what I need is to create a variables such as var title1 = “This is TITLE 1”; var title2 = “This is TITLE 2”; and so on. Then I need to run a loop:

for (i=i;i>=j;i=i-1) {
var whichTitle = ‘title_’ + i;

document.write(whichTitle);
}

The thing is rather than getting the text I’ve defined, I get title1 and title2 (not “This is TITLE 2”). For some reason, javascript’s not considering the original variables as the one’s needed to be passed. I’m sure I’m facing this the wrong way. HELP!!!

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@astupidnameJun 04.2009 — Change this:
var whichTitle = 'title_' + i;[/QUOTE]
to the following:
[CODE]var whichTitle = window['title' + i]; //assuming you have global variables named in format: var title[number in this character position] = 'whatever'[/CODE]
Copy linkTweet thisAlerts:
@astupidnameJun 04.2009 — Althought actually,
Basically, what I need is to create a variables such as var title1 = "This is TITLE 1"; var title2 = "This is TITLE 2";[/QUOTE]
This is what arrays are for.... rather than cluttering up the global namespace with a pile of variables each defining a single string, stick all the strings in an array and loop through the array instead.
Copy linkTweet thisAlerts:
@manlomasanauthorJun 04.2009 — Arrays was the way to go (or the first that worked at least!!)

Thanks guys. Hope I can pay you all back sometime.
×

Success!

Help @manlomasan 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 6.16,
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: @nearjob,
tipped: article
amount: 1000 SATS,

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

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...