代碼很簡單,我對編程很陌生。你輸入你需要的分數和游戲的結果,輸出就是分數所需的游戲時間。
它有效,我的問題是我應該如何將輸出轉換為 HH:MM 格式?我嘗試了 if/else 回圈,但作業量很大,更不用說它非常原始和硬編碼。回圈是答案嗎?我應該從頭開始嗎?
先感謝您!
function passPoints(input) {
let gameResult = String(input[0]);
let pointsNeeded = Number(input[1]);
let pointsPerMinute = 0;
if (gameResult == 'w') {
pointsPerMinute = 6;
} else if (gameResult == 'l') {
pointsPerMinute = 4;
}
let minutesOfGameplayNeeded = pointsNeeded / pointsPerMinute;
console.log(minutesOfGameplayNeeded)
}
uj5u.com熱心網友回復:
這是我將如何處理它。使用模數除以 60 得到 h:m
// as a helper function
const getTimeReadout = m => {
let a = [Math.floor(m / 60), Math.floor(m % 60)]
return a.map(t => ('0' t).slice(-2)).join(':')
}
在這里,它被集成到您的代碼中:
顯示代碼片段
function passPoints(input) {
let gameResult = String(input[0]);
let pointsNeeded = Number(input[1]);
let pointsPerMinute = 0;
if (gameResult == 'w') {
pointsPerMinute = 6;
} else if (gameResult == 'l') {
pointsPerMinute = 4;
}
let m = pointsNeeded / pointsPerMinute
let minutesOfGameplayNeeded = [Math.floor(m / 60), Math.floor(m % 60)];
// now it's in an array so we can iterate it below (adding the zero if needed)
minutesOfGameplayNeeded = minutesOfGameplayNeeded.map(t => ('0' t).slice(-2)).join(':')
console.log(minutesOfGameplayNeeded)
}
passPoints(['w', 427]);
同樣的事情,但我稍微優化了你的代碼:
顯示代碼片段
function passPoints(input) {
[gameResult, pointsNeeded] = input
let pointsPerMinute = gameResult == 'w' ? 6 : gameResult == 'l' ? 4 : 0;
let m = pointsNeeded / pointsPerMinute;
return [Math.floor(m / 60), Math.floor(m % 60)].map(t => ('0' t).slice(-2)).join(':')
}
console.log(passPoints(['w', 427]));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/460815.html
標籤:javascript
