到目前為止,我是一個非常新的初學者,現在正在練習“條件”。所以這是我現在卡住的練習。但是,我很想對其進行編碼,但我不知道如何真正開始它。請幫我解決。非常感謝!下面是練習的正文。
??宣告一個名為 randomStopLight 的函式。
??它應該創建一個從0到10的亂數。如果生成的數字小于3,函式應該回傳“??Red”。如果生成的數字在 3 到 6 之間(包括兩者),則應回傳“Yellow”。如果生成的數字大于 6,則應回傳“??Green”。
uj5u.com熱心網友回復:
function randomStopLight() {
const randomNum = Math.random() * 10 // Math.random() returns a
// random number between 0 and 1 so we multiply by 10 to get a
// number between 0 and 10
if(randomNum < 3) return 'Red' // check if the number is less than 3
else if(randomNum < 6) return 'Yellow' // check if the number is less than 6 it will only get here if it's bigger than 3 so no need to check if it's not smaller than 3
else return 'Green' // and if it's not smaller than 3 or 6 it must be bigger so no need for any condition so a plain old else is enough to return Green
}
uj5u.com熱心網友回復:
Math.random回傳一個介于 0 和 1 之間的偽亂數(不包括 1),您可以將此數字乘以最大范圍(此處為 11),然后可以Math.floor()得到小于或等于傳遞給它的數字的最大整數。
然后你可以使用一個簡單的if-else塊或switch塊來回傳預期的結果。
function randomStopLight() {
const randomNum = Math.floor(Math.random() * 11);
if (randomNum < 3)
return 'red';
else if (randomNum >= 3 && randomNum <= 6)
return 'yellow';
else
return 'green';
}
for (let i = 0; i < 5; i )
console.log(randomStopLight());
uj5u.com熱心網友回復:
function randomStopLight() {
const num = Math.floor(Math.random() * 11);
if (num < 3) {
return '??Red';
}
if (num > 6) {
return '??Green'
}
return '??Yellow';
}
另一種方式,更少的行:
function randomStopLight() {
const num = Math.floor(Math.random() * 11) ;
return num > 3 ? '??Red' : (num < 6 ? '??Green' : '??Yellow')
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/346437.html
標籤:javascript if 语句 数学
上一篇:為什么FileAge回傳意外值?
下一篇:通過匹配部分值合并兩個物件陣列
