javascript在调用函数之前先分配变量

时间:2018-12-01 00:20:58

标签: javascript variable-assignment

编辑添加:*********** @melomene不喜欢我调用的roll和rollP数组。但是,它们被声明为数组。我已经在下面添加了完整的javascript文件。


我有2个小数组:roll []和rollP []。他们每个只有2个项目。当运行功能'checkDouble6()'时,像这样将roll的内容保存到rollP中。

rollP = roll;

这是代码中将roll值分配给rollP的唯一位置。

以某种方式,即使此语句在checkDouble6()函数中,有时也会在调用checkDouble6()函数之前发生这种情况。

我为console.logs发疯了,试图找出答案。 Anyhoo ..

以下是代码块,这些代码块用于说明玩家单击(导致虚拟骰子滚动),checkDouble6()函数和“保持”函数时发生的情况。持牌是指玩家决定保留当前得分并允许下一位玩家进行转牌。

由于某种原因,玩家第一次切换时不会发生抢占式变量分配。我认为这是因为switchPlayer()函数将rollP重新分配为[0,0]。但是之后,每次玩家掷骰时,变量数组rollP都会在调用checkDouble6()函数之前获取roll的值。

document.querySelector('.btn-roll').addEventListener('click', function(){

    if (isGamePlaying){
        //1.Random number is generated
        roll[0] = Math.floor(Math.random()*6) + 1;
        roll[1] = Math.floor(Math.random()*6) + 1;

        //2.Display the result
        document.querySelectorAll('.dice').forEach(diceClass=>diceClass.style.display = 'block');
        document.getElementById('dice1').src = 'dice-'+roll[0]+'.png';
        document.getElementById('dice2').src = 'dice-'+roll[1]+'.png';

        console.log('roll before checkDouble6: '+roll);
        console.log('rollP before checkDouble6: '+rollP);
        checkDouble6();
        console.log('roll after checkDouble6: '+roll);
        console.log('rollP after checkDouble6: '+rollP);

        //3.Update the round score IF the rolled number is not a 1
        if( roll[0]!== 1 && roll[1]!==1){
            //Add score
            roundScore += roll[0]+roll[1];
            document.getElementById('current-'+activePlayer).textContent = roundScore;

        }else{
            //Next player's turn.
            roundScore = 0;
            switchPlayer();
        }  
    }
});

function checkDouble6(){
    if (roll[0]===6 &&(roll[1]===6 || rollP[0]===6 || rollP[1]===6)){
        //lose whole global score. Next player's turn.
        scores[activePlayer]=0;
        console.log('roll during checkDouble6: '+roll);
        console.log('roll during checkDouble6: '+rollP);
        switchPlayer();
    } else if (roll[1]===6 &&(rollP[0]===6 || rollP[1]===6)){
        //lose whole global score. Next player's turn.
        scores[activePlayer]=0;
        console.log('roll: '+roll);
        console.log('rollP: '+rollP);
        switchPlayer();
    } else{
        //everything is fine
    }
    rollP = roll;
    console.log('roll at end of checkDouble6 function: '+roll);
    console.log('rollP at end of checkDouble6 function: '+rollP);
};

console.logs太多了,因为我试图弄清楚这是怎么发生的。下面是“保持”功能。同样,这可能不是因为将rollp设置为[0,0]而在玩家的转弯后立即发生的。

document.querySelector('.btn-hold').addEventListener('click', function(){
    if (isGamePlaying){
        //Add current score to global score
        scores[activePlayer] += roundScore;

        //Update UI
        document.getElementById('score-'+activePlayer).textContent = scores[activePlayer];

        //Check if player won the game
        if (scores[activePlayer]>=100){
            //they won
            document.getElementById('name-'+activePlayer).textContent = 'WINNER!';
            document.querySelector('.dice').style.display = 'none';
            document.querySelector('.player-'+activePlayer+'-panel').classList.remove('active');
            document.querySelector('.player-'+activePlayer+'-panel').classList.add('winner');
            isGamePlaying = false;
        }else{
            //they didn't win. Next player's turn.
            switchPlayer();
        }
    }

});

这是整个shebang:

var scores, roundScore, activePlayer, isGamePlaying;
var roll = new Array(2);
var rollP = new Array(2);

initializeGame();

//document.querySelector('#current-0').textContent = dice;
//document.querySelector('#current-'+activePlayer).innerHTML = '<em>'+dice+'</em>';

document.querySelector('.btn-roll').addEventListener('click', function(){
    // This would be an anonymous function

    if (isGamePlaying){
        //1.Random number is generated
        roll[0] = Math.floor(Math.random()*6) + 1;
        roll[1] = Math.floor(Math.random()*6) + 1;

        //2.Display the result
        document.querySelectorAll('.dice').forEach(diceClass=>diceClass.style.display = 'block');
        document.getElementById('dice1').src = 'dice-'+roll[0]+'.png';
        document.getElementById('dice2').src = 'dice-'+roll[1]+'.png';

        console.log('roll before checkDouble6: '+roll);
        console.log('rollP before checkDouble6: '+rollP);
        checkDouble6();
        console.log('roll after checkDouble6: '+roll);
        console.log('rollP after checkDouble6: '+rollP);

        //3.Update the round score IF the rolled number is not a 1
        if( roll[0]!== 1 && roll[1]!==1){
            //Add score
            roundScore += roll[0]+roll[1];
            document.getElementById('current-'+activePlayer).textContent = roundScore;

        }else{
            //Next player's turn.
            roundScore = 0;
            switchPlayer();
        }  
    }
});

document.querySelector('.btn-hold').addEventListener('click', function(){
    if (isGamePlaying){
        //Add current score to global score
        scores[activePlayer] += roundScore;

        //Update UI
        document.getElementById('score-'+activePlayer).textContent = scores[activePlayer];

        //Check if player won the game
        if (scores[activePlayer]>=100){
            //they won
            document.getElementById('name-'+activePlayer).textContent = 'WINNER!';
            document.querySelector('.dice').style.display = 'none';
            document.querySelector('.player-'+activePlayer+'-panel').classList.remove('active');
            document.querySelector('.player-'+activePlayer+'-panel').classList.add('winner');
            isGamePlaying = false;
        }else{
            //they didn't win. Next player's turn.
            switchPlayer();
        }
    }

});

function switchPlayer(){
    // Set round scores to 0
    roundScore = 0;
    roll = [0,0];
    rollP = [0,0];
    document.getElementById('current-0').textContent = 0;
    document.getElementById('current-1').textContent = 0;

    // Toggle the visuals 
    document.querySelector('.player-0-panel').classList.toggle('active');
    document.querySelector('.player-1-panel').classList.toggle('active');

    //change active player from one to the other
    console.log('Switch from player-'+activePlayer);
    activePlayer === 1 ? activePlayer = 0 : activePlayer = 1;
    console.log('to player-'+activePlayer);
};

document.querySelector('.btn-new').addEventListener('click', initializeGame);

function initializeGame(){
    roll = [0,0];
    rollP = [0,0];
    roundScore = 0;
    scores = [0,0];
    activePlayer = 0;  

    document.querySelectorAll('.dice').forEach(diceClass => diceClass.style.display = 'none');
    document.getElementById('score-0').textContent = '0';
    document.getElementById('score-1').textContent = '0';
    document.getElementById('current-0').textContent = '0';
    document.getElementById('current-1').textContent = '0';
    document.getElementById('name-0').textContent = 'Player 1';
    document.getElementById('name-1').textContent = 'Player 2';
    document.querySelector('.player-0-panel').classList.remove('winner');
    document.querySelector('.player-1-panel').classList.remove('winner');
    document.querySelector('.player-0-panel').classList.remove('active');
    document.querySelector('.player-1-panel').classList.remove('active');
    document.querySelector('.player-0-panel').classList.add('active');

    isGamePlaying = true;

};

function checkDouble6(){
    if (roll[0]===6 &&(roll[1]===6 || rollP[0]===6 || rollP[1]===6)){
        //lose whole global score. Next player's turn.
        scores[activePlayer]=0;
        console.log('roll during checkDouble6: '+roll);
        console.log('roll during checkDouble6: '+rollP);
        switchPlayer();
    } else if (roll[1]===6 &&(rollP[0]===6 || rollP[1]===6)){
        //lose whole global score. Next player's turn.
        scores[activePlayer]=0;
        console.log('roll: '+roll);
        console.log('rollP: '+rollP);
        switchPlayer();
    } else{
        //everything is fine
    }
    rollP = roll;
    console.log('roll at end of checkDouble6 function: '+roll);
    console.log('rollP at end of checkDouble6 function: '+rollP);
};

1 个答案:

答案 0 :(得分:1)

在执行roll = rollP时,您正在将引用从rollP复制到roll,这意味着roll和rollP将指向相同的内存位置。

例如如果将某物推入纸卷,则在rollP中将完全相同,反之亦然。

如果我正确理解,您只想做roll[0] = rollP[0]; roll[1] = rollP[1];