0

I need help with creating a “dynamic variable” I’m not even sure if this is possible in JavaScript but if anyone knows how to do it please help . Here’s an example of what I need.

  1. Lets say we have selected 3 elements from the DOM.
let person1 = document.querySelector(".person-1");
let person2 = document.querySelector(".person-2");
let person3 = document.querySelector(".person-3");
  1. We want to edit one of those elements with an if/else statement. I know the beginning of all of those variables is person but the end is different (1,2,3), how can I dynamically call the appropriate variable?
Let endOfName = 3;

// ***Problem Below***
If(person[endOfName] === “Anything”){
    console.log("Do whatever…");
};

// ***What I want***
If(person3 === “Anything”){
    console.log("Do whatever…");
};
Bozinoski
  • 1
  • 1
  • 2
    Put them in an array and reference them by index. – takendarkk Jul 17 '19 at 00:44
  • 1
    Any time you are tempted to make variables like `person1`, `person2` ... `personN` you should be using an array: `person = [ ]` and then it's dynamic: `person[0], person[1]...`. – Mark Jul 17 '19 at 00:51
  • [Here](https://stackoverflow.com/questions/2051678/getting-all-variables-in-scope) is well defined answer, related to your question. – skazska Jul 17 '19 at 04:13

1 Answers1

0

You may try to cover the elements in map declaration and call them dynamically

let personMap = {
    person1: document.querySelector(".person-1"),
    person2: document.querySelector(".person-2"),
    person3: document.querySelector(".person-3")
}


If(personMap[`person${endOfName}`] === “Anything”){
    console.log("Do whatever…");
};
Vitalii Shevchuk
  • 1,111
  • 7
  • 4