【问题标题】:Javascript returns undefined in html tags but shows result in developer consoleJavascript 在 html 标记中返回未定义但在开发者控制台中显示结果
【发布时间】:2019-02-03 19:14:55
【问题描述】:

我在 html 页面的 textarea 上呈现此代码的输出时遇到问题,但它运行并在控制台上显示正确的输出。下面是html和javascript代码..谢谢

<body>
<div class="input">
    <div class="numb">
        <form class="form-group" name="number" id="number">
            <input id="textbox" type="text" name="textbox" placeholder="Enter N">
            <button type="button" name="submit" id="button" onclick="final()">Get Matrix</button>
        </form>

    </div>
    <div class="result">
        <textarea id="spiral" name="spiral" placeholder="matrix"></textarea>
    </div>
</div>

function createMatrix(size) {
const array = [];
for (let i = 0; i < size; i++) {
    array.push(new Array(size));
}
return array;}

function spiral(input) {
const output = createMatrix(input);
let n = 1;
let a = 0;
let b = input;
let direction = 0; // 0 = right, 1 = down, 2 = left, 3 = up
let directionFlip = true;
let x = 0;
let y = 0;
while (n <= (input * input)) {
    output[x][y] = n;
    n++;
    a++;
    if (a >= b) {
        a = 0;
        if (direction === 0 || direction === 2 && directionFlip) {
            b--;
        }
        directionFlip = !directionFlip;
        direction = (direction + 1) % 4;
    }

    switch(direction) {
        case 0:
            x++;
            break;
        case 1:
            y++;
            break;
        case 2:
            x--;
            break;
        case 3:
            y--;
            break;
    }
}
return output;}

一个打印函数来定义这个形式的矩阵顺序螺旋 1 2 3 8 9 4 7 6 5

function print(input, paddingChar) {
const longest = (input.length * input.length).toString().length;
const padding = paddingChar.repeat(longest);
for (let y = 0; y < input.length; y++) {
    let line = "";
    for (let x = 0; x < input.length; x++) {
        line += (padding + input[x][y]).slice(-longest) + " ";
    }
    console.log(line.toString());
}}

以及在html页面中调用它并返回方阵的函数

function final() {
input = document.getElementById("textbox").value;
let text = print(spiral(input), " ");
document.getElementById("spiral").innerHTML = text}

所以如果我从页面输入 n,我会得到 n 的矩阵,显示在开发者控制台中,但不在 html 页面节点中

【问题讨论】:

  • 您的print 函数不返回任何内容,因此let text = print(spiral(input), " "); 不会将输出放入text

标签: javascript html matrix console spiral


【解决方案1】:

你没有从 print 函数返回任何东西;这里更新了 fiddle 以连接文本并返回矩阵中的文本

https://jsfiddle.net/gowrimr/mjvn3fru/7/

`let text = ''

在打印功能控制台后添加:

text = text+line.toString()+'\n'

终于做一个return text

【讨论】:

  • 谢谢大家...我通过更改 theconsole.log(line.toString());
【解决方案2】:

您的print 函数没有返回值,因此textundefined。在 print 函数的末尾添加类似 return line.toString(); 的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 2014-10-22
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多