2017-08-17 77 views
5

我試圖讓做一個隨機數生成器生成的數字1到9之間的字符串,如果它產生的8,應該最後,然後顯示8停止生成。隨機數do-while循環與if語句

到目前爲止它打印1 2 3 4 5 6 7 8,但它不會生成隨機數字串,所以我需要知道如何使循環實際上生成隨機數字,如上所述,感謝任何幫助!

的Javascript

// 5. BONUS CHALLENGE: Write a while loop that builds a string of random 
integers 
// between 0 and 9. Stop building the string when the number 8 comes up. 
// Be sure that 8 does print as the last character. The resulting string 
// will be a random length. 
print('5th Loop:'); 
text = ''; 

// Write 5th loop here: 
function getRandomNumber(upper) { 
    var num = Math.floor(Math.random() * upper) + 1; 
    return num; 

} 
i = 0; 
do { 
    i += 1; 

    if (i >= 9) { 
     break; 
    } 
    text += i + ' '; 
} while (i <= 9); 


print(text); // Should print something like `4 7 2 9 8 `, or `9 0 8 ` or `8 
`. 
+3

'Math.ceil(的Math.random()* 7)+ 1'是你的朋友。 – tilz0R

+0

你的邏輯看起來有缺陷的。 – ABcDexter

回答

4

你可以做一個更簡單的方法:

的解決方案是push隨機生成的數字到一個數組,然後使用join方法,以加盟數組中的所有元素的字符串所需的。

function getRandomNumber(upper) { 
 
    var num = Math.floor(Math.random() * upper) + 1; 
 
    return num; 
 
} 
 
var array = []; 
 
do { 
 
    random = getRandomNumber(9); 
 
    array.push(random); 
 
} while(random != 8) 
 
console.log(array.join(' '));

+1

非常感謝!忘記陣列等。 – hannacreed

+0

@hannacreed,歡迎您。 –

1

的print()是一個函數,它的目標是打印文檔,你應該使用的console.log()在控制檯中顯示。

把一個布爾你的循環之前,例如var eightAppear = false

你的條件,現在看起來像do {... }while(!eightAppear)

那麼你的循環中產生的毗連你的字符串0至9 Math.floor(Math.random()*10) 一個隨機數。如果數字是eightAppeartrue

8的變化值,因爲它似乎是一個鍛鍊,我會告訴你它的代碼,不應該現在很難:)

1

不是因爲它的好,而是因爲我們可以(和我一樣發電機:)),用一個迭代器功能的替代(需要ES6):

function* getRandomNumbers() { 
 
    for(let num;num !==8;){ 
 
    num = Math.floor((Math.random() * 9) + 1); 
 
    yield num;  
 
    } 
 
} 
 

 
let text= [...getRandomNumbers()].join(' '); 
 
console.log(text);