Оператор if внутри функции - отношение к глобальной области видимости - PullRequest
0 голосов
/ 03 мая 2019

Я давно играю в одну простую DOM-игру.И я не могу понять, почему это так.Объяснение в коде ниже.Я не понимаю, почему одна переменная должна быть объявлена ​​внутри функции в операторе if, чтобы она работала, а не в глобальной области видимости.Я занимался этим буквально несколько часов и знаю, что это должно быть просто, но теперь это сводит меня с ума.

//this code does not work - if the var currentScore is declared in the global scope

var
    activePlayer = 1;
    btnRoll = document.querySelector(".btn-roll");
    diceImage = document.querySelector(".dice");
    diceImage.style.display="none";

//var currentScore selects a div - either the one from player 1 or 2

    currentScore = document.querySelector("#current-" + activePlayer);


    btnRoll.addEventListener ("click", function(){
        //after clicking roll dice - generate random num
        var diceNum = Math.floor(Math.random() * 6) + 1;
        diceImage.style.display="block";
        //view a correct image that is the generated number
        diceImage.src="dice-" + diceNum + ".png";
        //if the rolled number greater than one - add to the roundScore
        if (diceNum !== 1) {
            roundScore += diceNum;
//this below should change the text of 0 of a div for player 1 to text of the round score -which it does
            currentScore.textContent = roundScore;


        }
        //else its other players round
        else {
            roundScore = 0;
           if(activePlayer === 1) {
               activePlayer = 2;
  //when I console.log the active player it changes to 2

           }
           else {
               activePlayer = 1;


           }
        }

    });
//problem comes when its suppose to start again - it does recognize that its player 2 but the currentScore variable is stil #current-1 instead of #current-2. 

Чтобы он работал, переменная currentScore должна быть объявлена ​​таким же образом, но не в глобальной области видимости, а в первом операторе if.Почему?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...