0

I'm trying to build a simple yes/no diagnostic tool as part of learning Javascript. I'm coming absolutely unstuck on how to dynamically target an object's properties based on an external variable such as 'stage'.

For example,

Visually Stage 1 has a title and two buttons. When I select one of the buttons (say yes), the information is replaced with the stage 2 yes information.

So far I've created my objects (what I'm using to hold the info for each page).

function stage (name, title, button1, button2) {
  this.name = name;
  this.title = title;
  this.button1 = button1;
  this.button2 = button2;
}

var Stage1A = new stage ('Stage1A', 'success', 1, 2);
var Stage1B = new stage ('Stage1B', 'failure', 1, 2);

Now I'm trying to access the information inside each object based on the current stage number.

var stageNumber = 1;

function myFunction(){


 document.getElementById("title").innerHTML = ("Stage"+stageNumber+"A").title;
}

This returns a result of undefined. Can anyone point me in the right direction?

AJArms
  • 1
  • 1
    I'm not sure I completely understand the goal, but could you push each stage into an array and access them from there? That way the stage number can directly correlate to the array index (Or possibly a 2 dimensional array for your Stage1 A/B) – DBS Jul 28 '20 at 15:21
  • 2
    `("Stage"+stageNumber+"A")` <= you cannot dynamically refer to elements like this, without using eval. A better approach would be to use a parent object, such as `var stages = { Stage1A: }`, and then you can use `stages['Stage'+ stageNumber +'A']` to access it. – Taplar Jul 28 '20 at 15:22
  • 1
    Otherwise, `if (stageNumber === 1) { ... use Stage1A ... } else if (stageNumber === 2) { ... use Stage2B ... } else ...` – Taplar Jul 28 '20 at 15:24
  • 1) `const stages = {}` 2) `stages["StageA1"] = new stage(...)` –  Jul 28 '20 at 15:27
  • hey @DBS - just wanted to say the array choice was exactly right. Thank you for pointing me in the right direction :) – AJArms Jul 28 '20 at 17:06
  • @taplar, thanks for your comments, knowing I wasn't able to approach the problem like that was a big help. – AJArms Jul 28 '20 at 17:06

0 Answers0