I started learning to code recently and I'm having a problem with this self-challenge. My intent is to use a for-loop to cycle through the array containing color names, which represent buttons, to create a dynamic URL to audio files instead of individually adding the URL for the audio file to each button. Being a newbie, this code makes sense to me, but it isn't working. Using the browser "inspect" tool, I noticed the output for buttonColours[i]
is coming out as undefined. Please help me understand why!!!
var buttonColours = ["red","blue","green","yellow"];
var sounds = [];
for (var i = 0; i < buttonColours.length; i++){
$("."+buttonColours[i]+"").click(function(event){
// Add sound when button is clicked
sounds[i]= new Audio("sounds/"+buttonColours[i]+".mp3");
sounds[i].play();
// Add CSS class when button is clicked
$(".red").addClass("pressed");
setTimeout(function(){
$(".red").removeClass("pressed");
}, 200);
});
}
In addition to right answer of Sachin Nayak, another way to solve this issue is to use let
instead of var
. let
creates a variable inside the scope of the loop where var
will be a global variable that will be overwritten at every iteration. That means that with let
you don't overwrite the value, but create a new one at each iteration, thus the reference stays intact.
var buttonColours = ["red","blue","green","yellow"];
var sounds = [];
// Notice let i instead of var i.
for (let i = 0; i < buttonColours.length; i++) {
$("." + buttonColours[i]).click(function(event) {
// Add sound when button is clicked
sounds[i] = new Audio("sounds/" + buttonColours[i] + ".mp3");
sounds[i].play();
// Add CSS class when button is clicked
$(".red").addClass("pressed");
setTimeout(function() {
$(".red").removeClass("pressed");
}, 200);
});
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments