Uncaught ReferenceError: aresults не определен, но массив был определен - PullRequest
0 голосов
/ 27 января 2019

Я начинающий с JavaScript.

Когда я запускаю этот код, я получаю эту ошибку в Chrome's console: Uncaught ReferenceError: aresults is not defined

aresults - это array.Я думал, что инициализировал его до запуска For loop, который создает целые числа, которые будет хранить array.Но Chrome, кажется, говорит, что нет array.

Готовый код стремится создать определенное пользователем количество целых чисел от одного до 10, сохранить их в массиве и затем подсчитать числоцелых чисел в массиве, которые попадают между определенной пользователем целью и 10.

Что я здесь не так сделал?И как я могу это исправить?

Спасибо.

<!DOCTYPE html>
<head>
</head>

<body>

    <h2>Storyteller dice roller</h2>

    <!--User selects number of 10-sided dice to be rolled, and target number -->
    Number of dice: <input type="number" value="5" id="dice"><br>
    Difficulty: <input type="number" value="6" id="diff"><br>

    <!--Button executes the "roll" JavaScript function-->
    <button onclick="roll()">Roll</button>

    <script>

        function roll() {

            // initialize array to store results of "dice rolls"
            var aresults = [];

            // store user input of "Number of dice" as vdice variable
            var vdice = document.getElementById("dice").value;

            // store user input of "Difficulty" as vdiff variable
            var vdiff = document.getElementById("diff").value;

            // simulates rolling a number of 10-sided dice

            // for loop:
            // set vrolled to 0;
            // run loop if vrolled is less than dice;
            // increase vrolled by 1 each time loop is run
            // continue for as many times as there are "dice"
            for (vrolled = 0; vrolled <= vdice; vrolled++) {

                // Create a random number between 1 and 10
                var vresult=Math.floor(Math.random() * 10) + 1;

                // append the new dice roll result to the array
                aresults.push(vresult);

            }
        }

        // Display variable results in console
        console.log("Results array");
        console.log(aresults);
        console.log("Dice to be rolled");
        console.log(vdice);
        console.log("Roll result");
        console.log(vresult);
        console.log("Difficulty");
        console.log(vdiff);
        console.log("Dice rolled");
        console.log(vrolled);
    </script>
</body>

1 Ответ

0 голосов
/ 27 января 2019

Вы создаете все переменные внутри функции и пытаетесь получить к ним доступ снаружи.Определение с использованием var означает, что переменная будет доступна везде в области видимости.Это не всегда означает, что он будет доступен везде, то есть global Определение всех переменных вне области действия решит проблему, поскольку все переменные станут глобальными.

<!DOCTYPE html>
<head>
</head>

<body>

    <h2>Storyteller dice roller</h2>

    <!--User selects number of 10-sided dice to be rolled, and target number -->
    Number of dice: <input type="number" value="5" id="dice"><br>
    Difficulty: <input type="number" value="6" id="diff"><br>

    <!--Button executes the "roll" JavaScript function-->
    <button onclick="roll()">Roll</button>

    <script>
var aresults = [];
var vdice = document.getElementById("dice").value;
var vresult;
// store user input of "Difficulty" as vdiff variable
var vdiff = document.getElementById("diff").value;
        function roll() {

// initialize array to store results of "dice rolls"


// store user input of "Number of dice" as vdice variable


// simulates rolling a number of 10-sided dice

// for loop:
// set vrolled to 0;
// run loop if vrolled is less than dice;
// increase vrolled by 1 each time loop is run
// continue for as many times as there are "dice"
for (vrolled = 0; vrolled <= vdice; vrolled++) {

// Create a random number between 1 and 10
vresult=Math.floor(Math.random() * 10) + 1;

// append the new dice roll result to the array
aresults.push(vresult);

}
}

// Display variable results in console
console.log("Results array");
console.log(aresults);
console.log("Dice to be rolled");
console.log(vdice);
console.log("Roll result");
console.log(vresult);
console.log("Difficulty");
console.log(vdiff);
console.log("Dice rolled");
console.log(vrolled);
</script>
</body>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...