I am currently working on a javascript project for freeCodeCamp.com and i'm running into a problem with an array.
The project is to recreate the game 'Simon'. I am doing this by generating a random number and pushing that into an array (correctPattern), and then passing that array into a function that will play the audio/visual animations accordingly.
Problem is, I am using .shift on the function argument('sound') and calling the function recursivly to cycle through the array until it's empty. When I do this, somehow, it does this to the global array. So once the array is passed to the function, the function argument(array) is trimmed using shift and that applies to the global array as well.
I was under the impression that the function argument is equal to the item passed, but changing the argument will not affect the actual item passed. Is that incorrect? If so, how can I perform this function properly?
The only reason i'm using this method is because I need to use setTimeout for a delay in between audio files played in the game, otherwise they are all played at once.
Here is a copy of the important parts of the code.
//ANIMATE DIV BUTTON & PLAY RELATIVE AUDIO FILE
function animateMoveList(sound){
var soundFile = parseInt(sound[0]);
if(sound.length > 0){
$(".circle").removeClass('highlighted');
switch(soundFile){
case 1:
$(".circle1").addClass('highlighted');
audio1.play();
break;
case 2:
$(".circle2").addClass('highlighted');
audio2.play();
break;
case 3:
$(".circle3").addClass('highlighted');
audio3.play();
break;
case 4:
$(".circle4").addClass('highlighted');
audio4.play();
break
}
setTimeout(function(){
if(typeof sound !== 'string'){
sound.shift();
} else {
sound = [];
}
$(".circle").removeClass('highlighted');
animateMoveList(sound);
}, 1000);
}
}
function comparePatterns(){
}
//GENERATE RANDOM NUMBER, PUSH TO correctPattern AND PLAY ANIMATION
function pcMove(){
var randomNumber = Math.floor(Math.random() * 4 + 1);
correctPattern.push(randomNumber);
setTimeout(function(){
console.log(correctPattern);
animateMoveList(correctPattern);
userTurn = true;
}, 500);
}