返回的Javascript在html标签不确定的,但节目导致开发者控制台

问题描述 投票:0回答:2

我已经呈现在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的页面,我得到了开发者控制台,而不是在HTML页面中显示的节点在n矩阵

javascript html matrix console spiral
2个回答
1
投票

不必返回从打印功能什么;这里被更新小提琴来串联文本和矩阵返回文本

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

`let text = ''

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

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

最后做一个return text


0
投票

print功能母鹿没有返回值,因此textundefined。在你return line.toString();函数的末尾添加类似print

© www.soinside.com 2019 - 2024. All rights reserved.