I have an array of elemens, it is populated but all the members are undefined
.
// Result: [div.some-class, div.some-class, div.some-class, div.some-class]
console.log(myArray);
// Result: 4
console.log(myArray.length);
for(var i = 0 ; i < myArray.length; i++) {
setTimeout(function() {
console.log(myArray[i]); // <- This is "undefined"
console.log(myArray); // <- Successful log: has access to array
console.log(i); // <- Successful log: has access to "i"
// Uncaught TypeError: Cannot read property 'classList' of undefined
myArray[i].classList.add('yeah');
}, i * 200);
}
It works without timeout:
for(var i = 0 ; i < myArray.length; i++) {
// No errors -> it works
myArray[i].classList.add('yeah');
}
myArray
is a global value and timeout has access to every data it needs. Why it's still undefined?