【发布时间】: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