Javascript 在 html 标签中返回未定义,但在开发人员控制台中显示结果

标签 javascript html matrix console spiral

我在 html 页面的文本区域上渲染此代码的输出时遇到问题,但它运行并在控制台上显示正确的输出。下面是 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 页面节点中显示

最佳答案

您没有从打印函数返回任何内容;这里更新了 fiddle 以连接文本并返回矩阵中的文本

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

`let text = ''

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

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

最后做一个返回文本

关于Javascript 在 html 标签中返回未定义,但在开发人员控制台中显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54506561/

相关文章:

javascript - 用于导航用户的 Angular 三元运算符

c++ - 找不到n * n矩阵的行列式

c++ - 使用Eigen库进行sparseLU并显示L&U?

javascript - 如何在整个显示宽度上均匀分布 Squarespace 中的三个代码块?

javascript - JQuery 单击获取除该最近字段值之外的所有字段值(在多行中)

javascript - 在 Google Apps 脚本网络应用程序中动态插入脚本?

javascript - 让 jQuery 下拉菜单在悬停时显示

javascript - 在 docker compose 中运行后续迁移

javascript - 检查表格行中的单元格是否等于 0,如果是则隐藏该行

python - 并行排序两个 numpy 矩阵,逐行排序