代码很简单,我对编程很陌生。你输入你需要的分数和游戏的结果,输出就是分数所需的游戏时间。
它有效,我的问题是我应该如何将输出转换为 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)
}
最佳答案
这是我将如何处理它。使用模数除以 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]));
关于javascript - 我应该如何将输出从分钟转换为 HH :MM format?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71959789/