han*_*eed 6 javascript random loops do-while do-loops
我试图让一个随机数生成器生成一个1到9之间的数字串,如果它生成一个8,它应该显示最后8,然后停止生成.
到目前为止,它打印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
`.
Run Code Online (Sandbox Code Playgroud)
您可以通过更简单的方式进行操作:
解决方案是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(' '));Run Code Online (Sandbox Code Playgroud)