2017-07-04 26 views
0

只是爲了鍛鍊,我想打印出這個模式:的JavaScript絕對的初學者=停留在函數返回「未定義」

enter image description here

這裏是到目前爲止的代碼:

var even = " #"; 
 
    var odd = "# "; 
 
    var size = 4; 
 
    var rowCount = 1; 
 
    var lineLength = 1; 
 
    function writeOdd(size){ 
 
\t while(lineLength<=size){ 
 
\t \t document.write(odd) 
 
\t \t if(lineLength === size){ 
 
\t \t document.write("<br>") 
 
\t \t } 
 
\t \t lineLength++; 
 
\t } 
 
    } 
 
    function writeEven(size){ 
 
\t while(lineLength<=size){ 
 
\t \t document.write(even) 
 
\t \t if(lineLength === size){ 
 
\t \t document.write("<br>") 
 
\t \t } 
 
\t \t lineLength++; 
 
\t } 
 
    } 
 
\t \t if(rowCount <= size && rowCount % 2 !== 0) {document.write(writeEven(size));} 
 
    \t \t else if(rowCount <= size && rowCount % 2 === 0){document.write(writeOdd(size));} 
 
\t \t rowCount++;

我被困 - 第一行打印出來好,第二個給出「未定義」,就是這樣。

+0

取決於您何時調用第一個功能。如果在頁面解析後,'document.write'會清除所有以前的內容。在所有情況下,使用DOM操作方法而不是'document.write'。 – Teemu

+0

忘掉2k17中的document.write;) – Angels

+3

你正在嘗試document.write writeEven和writeOdd的返回值,這是未定義的。 – James

回答

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(); 
1

問題出在document.write(writeEven(size))document.write(writeOdd(size))writeEvenwriteOdd不明確地返回任何東西。當一個函數沒有顯式返回任何東西時,它將默認返回undefined。所以當這些函數返回時,undefined被傳入document.write,並寫入屏幕。

請注意document.write(writeOdd(size))從內到外進行評估。首先執行writeOdd(size)。然後它返回。返回值基本上取代它,給我們document.write(undefined)。然後執行document.write(undefined),並在屏幕上打印「未定義」。

有關返回值的更多信息,請查看https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Return_values

1

你的函數調用文件撰寫,因此無需調用writeEven和writeOdd時,還你錯過了一個while循環遞增行使用它,並且線路長度應該在每個功能

var even = "&nbsp;#"; 
 
    var odd = "#&nbsp;"; 
 
    var size = 4; 
 
    var rowCount = 1; 
 
    
 
    function writeOdd(size){ 
 
    var lineLength = 1; 
 
\t while(lineLength<=size){ 
 
\t \t document.write(odd) 
 
\t \t if(lineLength === size){ 
 
\t \t document.write("<br>") 
 
\t \t } 
 
\t \t lineLength++; 
 
\t } 
 
    } 
 
    function writeEven(size){ 
 
    var lineLength = 1; 
 
\t while(lineLength<=size){ 
 
\t \t document.write(even) 
 
\t \t if(lineLength === size){ 
 
\t \t document.write("<br>") 
 
\t \t } 
 
\t \t lineLength++; 
 
\t } 
 
    } 
 
    while (rowCount <= 5) { 
 
\t \t if(rowCount <= size && rowCount % 2 !== 0) {writeEven(size);} 
 
    \t \t else if(rowCount <= size && rowCount % 2 === 0){writeOdd(size);} 
 
\t \t rowCount++; 
 
}
被initialzed