获取未定义为函数输出

时间:2019-07-03 15:41:37

标签: javascript html

我制作了js代码,用于跟踪超过60000卷的每个骰子面的频率。我需要将其显示在网页上,但似乎无法正常进行。

我尝试将outputArea元素设置为一个名为refID的变量,然后将refID的innerText设置为函数输出,但是会在控制台中输出“未定义”。

    <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>

预期的输出是频率列表,但我一直在网页上看到一行显示“ undefined”的字。

1 个答案:

答案 0 :(得分:0)

Console.log未设置函数输出。这是通过return语句设置的,否则未定义。尝试以下方法:

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>