gpt4 book ai didi

javascript - 测试函数时未定义

转载 作者:行者123 更新时间:2023-11-30 09:19:45 25 4
gpt4 key购买 nike

所以我一直在研究制作星形图案的函数,但不知何故,当我“innerHTML”它时,我总是得到“未定义”。谁能帮我看看我做错了什么?

pOutput.innerHTML = square(3);
poutput.innerHTML = rectangle(2,3);

function square(x) {
var z;
for (var i = 1; i<=x; i++) {
for ( var j = 1; j<=x; j++) {
z += "*";
}
z += "<br>";
}
return z
}

function rectangle(x, y) {
var z;
for (var i = 1; i<=x; i++) {
for ( var j = 1; j<=y; j++) {
z += "*";
}
z += "<br>";
}
return z
}

最佳答案

你应该做 var z = "" 否则值是undefined,看这个:

var z;

console.log(z)

完整示例:

console.log(square(3));
console.log(rectangle(2,3));

function square(x) {
var z = "";
for (var i = 1; i<=x; i++) {
for ( var j = 1; j<=x; j++) {
z += "*";
}
z += "<br>";
}
return z
}

function rectangle(x, y) {
var z = "";
for (var i = 1; i<=x; i++) {
for ( var j = 1; j<=y; j++) {
z += "*";
}
z += "<br>";
}
return z
}

关于javascript - 测试函数时未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52504799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com