只是为了锻炼,我试图打印出这种模式:
到目前为止,这是代码:
var even = " #";
var odd = "# ";
var size = 4;
var rowCount = 1;
var lineLength = 1;
function writeOdd(size){
while(lineLength<=size){
document.write(odd)
if(lineLength === size){
document.write("<br>")
}
lineLength++;
}
}
function writeEven(size){
while(lineLength<=size){
document.write(even)
if(lineLength === size){
document.write("<br>")
}
lineLength++;
}
}
if(rowCount <= size && rowCount % 2 !== 0) {document.write(writeEven(size));}
else if(rowCount <= size && rowCount % 2 === 0){document.write(writeOdd(size));}
rowCount++;
我被卡住 - 第一行打印出来好,第二行给出“未定义”,就是这样。
答案 0 :(得分:1)
问题出在document.write(writeEven(size))
和document.write(writeOdd(size))
。 writeEven
和writeOdd
并未明确返回任何内容。当函数没有显式返回任何内容时,默认情况下它将返回undefined
。因此,当这些函数返回时,undefined
会被传递到document.write
,并被写入屏幕。
请注意document.write(writeOdd(size))
从内到外进行评估。首先执行writeOdd(size)
。然后它返回。返回值基本取代它,给我们document.write(undefined)
。然后执行document.write(undefined)
,并打印&#34; undefined&#34;到了屏幕。
查看https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Return_values以获取有关返回值的更多信息。
答案 1 :(得分:1)
你的函数调用document.write,所以在调用writeEven和writeOdd时不需要使用它,你也缺少一个用于递增行的while循环,并且应该在每个函数中初始化lineLength
var even = " #";
var odd = "# ";
var size = 4;
var rowCount = 1;
function writeOdd(size){
var lineLength = 1;
while(lineLength<=size){
document.write(odd)
if(lineLength === size){
document.write("<br>")
}
lineLength++;
}
}
function writeEven(size){
var lineLength = 1;
while(lineLength<=size){
document.write(even)
if(lineLength === size){
document.write("<br>")
}
lineLength++;
}
}
while (rowCount <= 5) {
if(rowCount <= size && rowCount % 2 !== 0) {writeEven(size);}
else if(rowCount <= size && rowCount % 2 === 0){writeOdd(size);}
rowCount++;
}
答案 2 :(得分:0)
function print() {
let flag = true;
for(let i = 0; i < 4; i++) {
for(let j = 0; j < 8; j++) {
flag ? process.stdout.write('#') : process.stdout.write(' ');
flag = !flag;
}
flag = !flag;
process.stdout.write('\n');
}
}
print();