0

I define three variables (just for example) as follows:

window.myCirclePlayer_0 = ...
window.myCirclePlayer_1 = ...
window.myCirclePlayer_2 = ...

Somewhere else in my code (pseu-code):

var index = 0 1 or 2; //index can be 0, 1 or 2, we don't know which yet

I then want to add the index to the window variable so it calls the correct method. This doesn't work though. Is something like this even possible?

window.myCirclePlayer_[index].doMethod();

1 Answer 1

1

You can do window['myCirclePlayer_' + index].doMethod() but you should consider another approach. When you see variables like foo_1 and foo_2 you should probably be using an array.

Than way you can do something like:

var circlePlayers = [
  ...,
  ...,
  ...
];

Then you can use the index more naturally like:

circlePlayers[index].doMethod();

You can also add more circlePlayers like:

circlePlayers.push(...);

I only used ... in the code examples above because that's what you used.

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

1 Comment

Brilliant. Thank you.

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.