温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - Getting undefined as function output

javascript - 获取未定义为函数输出

发布于 2020-03-27 12:02:48

我制作了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>

预期的输出是频率列表,但我不断在网页上得到一行“未定义”的字样。

查看更多

查看更多

提问者
ads21323
被浏览
12
ChrisM 2019-07-03 23:56

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>

发布
问题

分享
好友

手机
浏览

扫码手机浏览