0

我有以下代码尝试将时间字符串(例如“9:45”或简单地“9”)转换为秒,进行一些计算,然后再次以正确的 HH:MM 格式返回。虽然我成功地完成了例如“9:45”的格式,但当它只是“9”时,我似乎无法弄清楚如何做到这一点。它归结为使用 || 的 if 语句 和 != 运算符,但我无法开始工作,我的输出是NaN:NaN

这是我的代码:

    var the_time = "10";
    var the_travel_time = 643 // This is already given in seconds

    var hms = the_time;   // your input string

    if (hms != "11" || hms != "10" || hms != "9"|| hms != "8") {

    var a = hms.split(':'); // split it at the colons

    // minutes are worth 60 seconds. Hours are worth 60 minutes.
    var the_time_inSeconds = (+a[0]) * 60 * 60 + (+a[1]*60);

    } else {
    var the_time_inSeconds = parseInt(hms)
    var the_time_inSeconds = hms * 60 * 60;
    }

    //the following code calculates the leave time
    //the_travel_time is taken from google's api call

    var the_leave_time = the_time_inSeconds - the_travel_time;

    var leave_hours = Math.floor(the_leave_time / 60 / 60);

    var leave_minutes = Math.floor(the_leave_time / 60) - (leave_hours * 60);

var the_leave_format = leave_hours + ':' + leave_minutes.toString().padStart(2, '0');
4

1 回答 1

0

你在 if 条件下错误地处理了你的逻辑:

if(hms != "11" || hms != "10" || hms != "9"|| hms != "8") {
    // with this logic all the flow passes through here 
else {
    // never flows around here
}

一种选择是检查字符串的长度:

if( has.length > 1 ) {
    hms.split(':')
    // ...
} else {
   // ...
}

我建议您阅读此逻辑运算符

于 2020-05-03T14:42:10.777 回答