...

View Full Version : Resolved Variable name referencing in for loop.



mgentry
07-11-2012, 09:34 PM
I am new to Javascript. Trying to simplify some of my scripts with some loops. I have 75 variables, A1-A25, B1-B25, C1-C25. I am having difficulty getting the correct syntax for combining the variable, i, with my existing text and getting the desired result. I am hoping to use a loop similar to this:

[CODE]
for (i=1; i<26; i++)
{
ReportSurface.addSelectionByExpression(['A'+i]);
var ['mf_A'+i] = ReportSurface.getMassFlow();

ReportSurface.addSelectionByExpression(['B'+i]);
var ['mf_B'+i] = ReportSurface.getMassFlow();

AzoreReportSurface.addSelectionByExpression(['C'+i]);
var ['mf_C'+i] = ReportSurface.getMassFlow();
}
[CODE]


The purpose of the loop would be to eliminate the need for this code:

[CODE]
ReportSurface.addSelectionByExpression("A1");
var mf_A1 = ReportSurface.getMassFlow();
ReportSurface.addSelectionByExpression("B1");
var mf_B1 = ReportSurface.getMassFlow();
AzoreReportSurface.addSelectionByExpression("C1");
var mf_C1 = ReportSurface.getMassFlow();
ReportSurface.addSelectionByExpression("A2");
var mf_A2 = ReportSurface.getMassFlow();
ReportSurface.addSelectionByExpression("B2");
var mf_B2 = ReportSurface.getMassFlow();
AzoreReportSurface.addSelectionByExpression("C2");
var mf_C2 = ReportSurface.getMassFlow();
[CODE]

.....

etc, on to C25.

Any help is appreciated.

Old Pedant
07-11-2012, 10:24 PM
This can be done, using either eval("xxx") or global["xxx"], but the whole thing looks ugly, to me. Not to mention that eval() has horrible performance consequences and global means you are "polluting" the global variable space.

Is there some reason you really *WANT* 75 different variables? What are you then going to do with them?

Wouldn't it be better to do something like this:


var mf = new Object();
for (i=1; i<26; i++)
{
ReportSurface.addSelectionByExpression('A'+i);
mf['A'+i] = ReportSurface.getMassFlow();
ReportSurface.addSelectionByExpression('B'+i);
mf['B'+i] = ReportSurface.getMassFlow();
ReportSurface.addSelectionByExpression('C'+i);
mf['C'+i] = ReportSurface.getMassFlow();
}

???

Then later in your code, where you used stuff like


var foo = mf_A13 + mf_C22 * mf_B7;

you would instead do


var foo = mf.A13 + mf.C22 * mf.B7;

Yes, mf.A12 is the same as mf["A12"] per the rules of JavaScript.

mgentry
07-12-2012, 02:35 PM
This will work.

Thanks.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum