簡體   English   中英

我沒有得到|| 在 Javascript 中使用?= 時的運算符?

[英]Am I not getting the || operator when using != in Javascript?

我有以下代碼嘗試將時間字符串(例如“9:45”或簡單地“9”)轉換為秒,進行一些計算,然后再次以正確的 HH:MM 格式返回。 雖然我成功地完成了例如“9:45”的格式,但當它只是“9”時,我似乎無法弄清楚如何做到這一點。 它歸結為使用 || 的 if 語句 and,= 運算符,但我無法上班,我的 output 是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');

你在 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 {
   // ...
}

我建議您閱讀此邏輯運算符

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM