/    Sign up×
Community /Pin to ProfileBookmark

Javascript Dynamic variables names

I’m trying to create variable names on the fly in a for loop, something like below:

for i = 0; i<data.rows.length; i ++ {
var a + data.rows.[i].c[1].v = ‘ some value’;
var b + data.rows.[i].c[1].v = ‘ some value’;
var c + data.rows.[i].c[1].v = ‘ some value’;
}

My goal is to have the variable names like:
a1234 = ‘some value’;
b1234 = ‘some value’;
c1234 = ‘soome value’;

I keep getting error messages though. Does anyone have a good solution? Thanks!

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@N_CMay 05.2014 — try an object like this:

[code=html]
var results = {};

for i = 0; i<data.rows.length; i ++ {
results[a + data.rows.[i].c[1].v] = ' some value';
results[b + data.rows.[i].c[1].v] = ' some value';
results[c + data.rows.[i].c[1].v] = ' some value';
}
console.log(results);
console.log(results[a1234]);
console.log(results.a1234);
[/code]
Copy linkTweet thisAlerts:
@Sup3rkirbyMay 05.2014 — I don't know that you can create actual named variables on-the-fly in javascript. And even if it can be done (though not likely), there is a better way to go about this.

Objects (and arrays for that matter) are lovely things in javascript as they allow you to store a great deal of information in a very organized manor.
[CODE]
var $onTheFly = {};
for(i = 0; i<data.rows.length; i++){
$onTheFly["a" + data.rows.[i].c[1].v] = ' some value';
$onTheFly["b" + data.rows.[i].c[1].v] = ' some value';
$onTheFly["c" + data.rows.[i].c[1].v] = ' some value';
}
console.log($onTheFly["a1234"]); // Prints "some value" to the console
[/CODE]


Also, I'm not sure if this is just a matter of how you posted your code on the forum or not, but you don't appear to have any parentheses around your [B]for()[/B] loop parameters. Someone could correct me if I'm wrong but I'm fairly certain those are required (and thus would create an error otherwise).
Copy linkTweet thisAlerts:
@RunningDude87authorMay 05.2014 — Thank guys!!! Using an object to store data worked great for me. And I did have parentheses around the for loop, just typed it in wrong.
×

Success!

Help @RunningDude87 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.5,
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: @Yussuf4331,
tipped: article
amount: 1000 SATS,

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

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