mardi 16 juillet 2019

Calling a variable dynamically

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…");
};

Aucun commentaire:

Enregistrer un commentaire