0

[updated] hey im javascript beginner. console.log said ArrayOfinnerHTML[i] is undefined. I was expected "w". but its now working :( dunno why. here is code below.

var drum = document.querySelectorAll(".drum");
var ArrayOfinnerHTML = ['w','a','s','d','j','k','l'];
  for(var i = 0; i <drum.length; i++){
    drum[i].addEventListener("click",function(){
     var whatInnerHTML = this.innerHTML;
     console.log('console_log is : '+ ArrayOfinnerHTML[i]); //undefined
     console.log('console_log is : '+ ArrayOfinnerHTML[0]); //w
     if(whatInnerHTML === ArrayOfinnerHTML[i])
     {
        alert('yes'); //not working
     }
    });
  }

I've tried using console.log but...:(

beebly
  • 19
  • 2
  • 4
    Remove `;` from the first line `var ArrayOfinnerHTML;` . It should be `var ArrayOfinnerHTML = ['w','a','s','d','j','k','l'];` . Also `drum` is not defined . – Ashraf Mar 23 '22 at 04:39
  • 1
    [This came up recently](https://stackoverflow.com/q/71503820/1377002). – Andy Mar 23 '22 at 04:44
  • 3
    This looks like [the infamous loop problem](https://stackoverflow.com/q/750486/283366). Use `let i` instead of `var i`. In fact, never use `var` – Phil Mar 23 '22 at 04:55
  • @Phil Its working!! super thxs so much you are my hero! u r freaking genius awesome – beebly Mar 23 '22 at 04:59
  • 2
    seriously @Phil - you should've let the OP suffer how we pioneers did, use an IIFE in the loop, or call a function passing `i` ... (same-same) :D - kids these days don't know the pain we suffered – Bravo Mar 23 '22 at 05:16

0 Answers0