Warm tip: This article is reproduced from stackoverflow.com, please click
html javascript

Getting undefined as function output

发布于 2020-03-27 10:31:00

I made js code that tracks the frequency of each dice face over 60000 rolls. I need to display it on a web page, which I can't seem to properly do.

I tried setting the outputArea element to a variable called refID, then setting the innerText of refID to the function output, but that outputs an 'undefined' into the console.

    <div id="outputArea"></div>
            <script type="text/javascript">
                //declaring workspace variables
            function output()
            {
                let iteration, dice, n;

                //initializing variables
                iteration = 0;
                dice = [0,0,0,0,0,0,0];

                //iterating through 60000 values and logging each item to its corresponding face value
                while (iteration < 60000) {
                    // asign n to a random integer between 1 and 6
                    n = Math.floor((Math.random() * 6) + 1);
                    //increment 1 to each value of n
                    dice[n] += 1;
                    iteration = iteration + 1;
                }

                //display each element from dice
                for (var i = 1; i < dice.length; i++) {
                    console.log(i+  ":" + dice[i]);
                }
            }
            var refID = document.getElementById("outputArea")
            refID.innerHTML = output()
            </script>

The expected output is a list of frequencies, but I keep getting a single line that says 'undefined' on the webpage instead.

Questioner
ads21323
Viewed
13
ChrisM 2019-07-03 23:56

Console.log doesn't set a function output. That is set with a return statement or else is undefined. Try this instead:

function output() {
    let returnVal, outputString, iteration, dice, n;

    //initializing variables
    iteration = 0;
    dice = [0, 0, 0, 0, 0, 0, 0];

    //iterating through 60000 values and logging each item to its corresponding face value
    while (iteration < 60000) {
        // asign n to a random integer between 1 and 6
        n = Math.floor((Math.random() * 6) + 1);
        //increment 1 to each value of n
        dice[n] += 1;
        iteration = iteration + 1;
    }

    //display each element from dice
    for (var i = 1; i < dice.length; i++) {
        outputString = i + ":" + dice[i];
        console.log(outputString);
        if (!returnVal) {
            returnVal = outputString;
        } else {
            returnVal = returnVal + "\n" + outputString;
        }

    }
    return returnVal;
}
var refID = document.getElementById("outputArea")
refID.innerHTML = output()
<body>
<div id="outputArea" style="white-space:pre-wrap"></div>
</body>