這個問題在這里已經有了答案: 為什么我的字串開頭有“未定義”文本? (3 個回答) 18 小時前關閉。
我正在撰寫一些代碼,該代碼首先在 1-6 (getRand6) 之間提取一個亂數。
然后它回圈一個 while 陳述句,次數與為 getRand6 提取的任何數字一樣多。回圈的每個回圈都會根據 1-10 之間的另一個亂數 (getRand10) 提取一種顏色。
然后它創建一個帶有顏色名稱的 html 段落并將其添加到 allColors,然后從 getRand6 中減去 1。
當 getRand6 為 0 時,它退出 while 回圈并將 allColors 發送到 id 為“colors”的物件。
一切似乎都在作業,但隨著顏色名稱的出現,我在 allColors 的開頭得到了“未定義”。例如,粗略的頁面代碼將顯示如下內容:
undefined
<p>Red</p>
<p>Green</p>
<p>Red</p>
<p>Blue</p>
我敢肯定這是我忽略的一件簡單的事情,但我對這一切還是有點陌生??,并希望得到幫助。
getRand6 = Math.floor(Math.random()*6) 1;
var allColors;
while (getRand6 > 0) {
getRand10 = Math.floor(Math.random()*10) 1;
if (getRand10 > 0 && getRand10 < 4) {specColor = "Red";}
else if (getRand10 > 3 && getRand10 < 7) {specColor = "Green";}
else if (getRand10 > 6 && getRand10 < 10) {specColor = "Blue";}
else {specColor = "White";};
allColors = "<p>" specColor "</p>";
getRand6--;
}
document.getElementById ('colors').innerHTML = allColors;
uj5u.com熱心網友回復:
改變這個
var allColors;
進入這個
var allColors="";
您的問題是您將 = 與 allcolors 一起使用,但第一次 allcolor 未定義
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/482184.html
標籤:javascript 循环 随机的 while循环 不明确的
上一篇:如何比較兩個串列?
