我有一个像01:02:3
这样的字符串(它是一个时间),我想获得以秒为单位的总数值。因此预期输出为 3723。
const time = "1:02:3";
const timeNumeric = time.split(':').map(item => {
return Number(item)
});
function total() {
var totalTime = 0;
if (timeNumeric.length = 3) {
const num1 = timeNumeric[0] * 3600
const num2 = timeNumeric[1] * 60
const num3 = timeNumeric[2]
totalTime = num1 + num2 + timeNumeric[2]
} else if (timeNumeric.length == 2) {
const num2 = timeNumeric[1] * 60
const num3 = timeNumeric[2]
totalTime = num2 + num3
} else if (timeNumeric.length == 1) {
const num3 = timeNumeric[2]
totalTime = num3
} else {
console.log('nothing')
}
console.log(totalTime)
}
请记住,字符串中的值可能并不总是 3 个数字,可能是 2:45
或 30
,那么第三个选项值将不需要任何计算。
最佳答案
除了当前号码之外,您的代码是正确的。当您使用 *
时,JavaScript 会尝试转换为数字。但是,当您使用 +
时,如果两个变量之一是字符串,JavaScript 会尝试转换为字符串。
var getSeconds = function(time) {
return time.split(':').reduce(function(prev, curr) {
return prev * 60 + parseInt(curr, 10)
}, 0)
}
var total = getSeconds('01:02:03')
var total2 = getSeconds('2:34')
console.log(total, total2) // 3723 154
关于javascript - 使用javascript转换以分号分隔的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42016067/