0

.JS code:

const allButtonsToStore = document.getElementsByClassName("button");
let countingNewVariables = 0;
for (x=0; x < allButtonsToStore.length; x++) {
  allButtonsToStore[x].addEventListener("click", function(){
    let reason[countingNewVariables] = allButtonsToStore[x].innerHTML;
    console.log(reason[countingNewVariables]);
    countingNewVariables++;
  });
}

My question starts at let reason[countingNewVariables]. I want it to create a new variable for each button ar following: reason0, reason1, reason2, etc.

example above does not work. I've also tried let reason[countingNewVariables] and let (reason + countingNewVariables)

My question here is how do I let it create a new variable every time, where the name of the variable = reason + countingNewVariables

Edit after suggestion:

const allButtonsToStore = document.getElementsByClassName("button");
let reason = [];
for (x=0; x < allButtonsToStore.length; x++) {
  allButtonsToStore[x].addEventListener("click", function(){
    reason[x] = this.textContent;
    console.log(reason[x]);
  });
}
number42
  • 107
  • 7
  • 5
    No, you do *not* want to create a new variable for each button. Believe you me. You may want an *array* of buttons, or an *object* of buttons. But you certainly don't want *variable variables.* – deceze Feb 04 '20 at 11:50
  • 2
    What you can do is declare the `reason` above your foorloop as an array (or object - depends on your usage). `let reason = []; for (x=0; x < allButtonsToStore.length; x++) { reason[x] = 'whatever' }` now you can access the reason – I am L Feb 04 '20 at 11:50
  • @IamL Thanks! Only It's always outputting reason20 (I do have 20 buttons but reason1 does not exist for example) – number42 Feb 04 '20 at 12:10
  • 1
    @number42 it you should access it as an array like `reason[1]` or `reason[20]` – I am L Feb 04 '20 at 12:12
  • @IamL I'm afraid still not. I think I'm doing something wrong. I've entered a new block of code and adjusted according to your suggestion. Maybe you will notice what I'm doing wrong? It's giving me undefined when I console log reason[0] in chrome. The console log in the javascript is working tho – number42 Feb 04 '20 at 12:19
  • 1
    @number42 hmmm seems to be correct - can you try logging reason after the for loop and see what it contains? – I am L Feb 04 '20 at 12:22
  • It's also undefined unfortunately – number42 Feb 04 '20 at 12:28
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/207178/discussion-between-number42-and-i-am-l). – number42 Feb 04 '20 at 12:32
  • See https://stackoverflow.com/q/750486/476… – deceze Feb 04 '20 at 13:19

0 Answers0