Copy link to clipboard
Copied
Hi, guys. I´m pretty new to all this stuff. I´m making a project using the normal html5 canvas, and my question is: can I make reference to an object using a common name + a variable?
For example: Let´s say I have 10 objects in my scene; they are all instance named the same except for a number at the end. That is: Object1, Object2, Object3, etc.
And I have a variable that changes when I click a button. It can go from 1 to 10. Let´s say it´s called “Number” (var Number = 1;)
Is it possible to write something like: this.”Object” + Number.visible = false;?
So when the variable is 2, the second object disappears, but when it´s 10, the tenth object disappears and so on.
The idea is to avoid writing 10 “Ifs” or manually defining an array of 10, because, in some cases, I would need to reference 60 objects or more.
Thanks a lot in advance. I know that it may be a very simple question, but I can´t find the answer.
1 Correct answer
Bracket notation.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
this["object" + n].visible = false;
BTW, don't ever use "Number" as a variable name. Or "String", or "Array", or "Object". Name variables after that they're for, not what they are. If it's a simple counter, just use a single-letter name. "i" is traditional.
Copy link to clipboard
Copied
Bracket notation.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
this["object" + n].visible = false;
BTW, don't ever use "Number" as a variable name. Or "String", or "Array", or "Object". Name variables after that they're for, not what they are. If it's a simple counter, just use a single-letter name. "i" is traditional.
Copy link to clipboard
Copied
Thanks a lot! It worked.
I tried a lot of different syntaxes, but avoided the brackets cause I thought they were only for arrays.

