![](/img/trans.png)
[英]OOO javascript: object self reference returns undefined but console shows it exists
[英]Javascript returns undefined in html tags but shows result in developer console
我在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页面节点中
您没有从打印功能返回任何内容; 这里更新了小提琴以连接文本并以矩阵形式返回文本
https://jsfiddle.net/gowrimr/mjvn3fru/7/
`let text = ''
在控制台中的打印功能后添加:
text = text+line.toString()+'\n'
终于做一个return text
您的print
函数不会返回值,因此text
是undefined
。 添加类似return line.toString();
在print
功能的末尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.