0

Firstly appologies for the poor title, not sure how to explain this in one line.

I have this Javascript function (stripped down for the purpose of the question)...

function change_col(zone){

    var objects= zone1227.getObjects();

}

I am passing in an integer into the function. Where I have "zone1227", I want that 1227 to be the integer I pass in.

I've tried this;

var zonename = "zone" + zone;

var objects= zonename.getObjects();

but that doesn't work.

Is this possible? The functions do exist for every possible integer passed in, but I was hoping to keep the code compact rather than a long list of if statements with hardcoded function names.

1
  • 5
    Let me just say this is undoubtedly an incorrect way to architect your application. Commented Sep 12, 2012 at 18:57

2 Answers 2

2

Since zone1227 is apparently a global variable, it can also be written as window.zone1227 or as window['zone1227']. This means that you can achieve what you describe, by writing this:

function change_col(zone){

    var objects= window['zone' + zone].getObjects();

}

Nonetheless, I agree with Interrobang's comment above. This is not a good way to accomplish whatever it is that you really want to accomplish. You should not be referring to global variables via strings containing their names.

Sign up to request clarification or add additional context in comments.

Comments

0

No, you cannot refer to a variable with the value of a string, nor can you concatenate anything onto a variable name. EDIT: turns out you can. You still shouldn't.

Yes, you can avoid using a long hard-coded if/elseif sequence: use an array.

Then you can say this:

function change_col(arr, i)
{
    var objects= arr[i].getObjects();
}

And the call would be something like:

change_col(zone, 1227);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.