在影响作为参数传递的全局数组的函数参数上使用 .shift()

Using .shift() on function argument which affects the global array that is passed as the argument

我目前正在为 freeCodeCamp.com 开发一个 javascript 项目,我 运行 遇到了数组问题。

该项目是重新创建游戏 'Simon'。我这样做是通过生成一个随机数并将其推入一个数组 (correctPattern),然后将该数组传递给一个函数,该函数将相应地播放 audio/visual 动画。

问题是,我在函数参数 ('sound') 上使用 .shift 并递归调用函数以循环遍历数组,直到它为空。当我这样做时,它会以某种方式对全局数组执行此操作。因此,一旦将数组传递给函数,就会使用 shift 修剪函数参数(数组),这也适用于全局数组。

我的印象是函数参数等于传递的项目,但更改参数不会影响实际传递的项目。那是不正确的吗?如果是这样,我该如何正确执行此功能?

我使用这种方法的唯一原因是我需要使用 setTimeout 在游戏中播放的音频文件之间进行延迟,否则它们会同时播放。

这是代码重要部分的副本。

//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);

        }

Javascript 数组是通过引用传递的,如果你在函数内部对数组进行任何更改,这些更改将保存在原始数组中。

按值传递数组(传递数组的副本)这意味着对传递的数组所做的更改不会保存在原始数组中。这可以通过使用原生数组方法——“slice()”——如任何 javascript language reference 中所述。在这种情况下,“切片”方法将 return 数组的浅表副本。

参考文献:

  1. Mastering Javascript Arrays
  2. Javascript Arrays – passing by reference or by value?