javascript - 使用javascript转换以分号分隔的字符串

标签 javascript regex

我有一个像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:4530,那么第三个选项值将不需要任何计算。

最佳答案

除了当前号码之外,您的代码是正确的。当您使用 * 时,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/

相关文章:

javascript - 使用自己的参数触发点击事件(首先是 JavaScript,替代 JQuery)

javascript - Animate Bootstrap 卡标题内容

javascript - 使用固定的左 div 水平滚动

java - 在已知值之前对多个数字进行分组

使用 sed|awk 和组进行替换的正则表达式

java - JAVA从字母表的相反端找到对应的字母并递归地从字符串中删除

javascript - 添加到 functions.php 时,Google Analytics 事件跟踪代码会破坏 wordpress 站点

javascript - 如何用Javascript获取确切的 child 数量

c - C 程序中读取日期和时间的正则表达式

java - 骡子 ESB : Expression Filter with regex() function