簡體   English   中英

為什么我的代碼有時返回 undefined

[英]Why does my code sometimes return undefined

我試圖顯示兩個不同的數字,但每次結果都相同,有時顯示未定義。 有沒有什么辦法解決這一問題?

 var usedCard = [0]; var columnB = Math.floor(Math.random()*16); function columnBB(){ if (usedCard.includes(columnB)){ columnB = Math.floor(Math.random()*16); columnBB(); } else {return columnB}; } document.getElementById("B1").innerHTML = columnBB(); usedCard.push(columnB); columnB = Math.floor(Math.random()*16) document.getElementById("B2").innerHTML = columnBB();
 <!DOCTYPE html> <html> <body> <table> <tr> <td id="B1"></td> <td id="B2"></td> </tr> </table> </body> </html>

您正在使用遞歸。 當函數調用自身時,它永遠不會返回,因為如果從未調用過 if 分支,它只會調用 else 分支。 刪除 else 並簡單地返回,你應該很好。

 var usedCard = [0]; var columnB = Math.floor(Math.random()*16); function columnBB(){ if (usedCard.includes(columnB)){ columnB = Math.floor(Math.random()*16); columnBB(); } return columnB; } document.getElementById("B1").innerHTML = columnBB(); usedCard.push(columnB); columnB = Math.floor(Math.random()*16) document.getElementById("B2").innerHTML = columnBB();
 <!DOCTYPE html> <html> <body> <table> <tr> <td id="B1"></td> <td id="B2"></td> </tr> </table> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM