簡體   English   中英

可讀性持續時間的格式? JavaScript的

[英]Format for human readable duration? JavaScript

我有此function ,可讓人們閱讀。

function formatDuration (seconds) {
    function numberEnding (number) {
        return (number > 1) ? 's' : '';
    }
    if (seconds > 0){
        var years = Math.floor(seconds / 31536000);
        var days = Math.floor((seconds % 31536000) / 86400);
        var hours = Math.floor(((seconds % 31536000) % 86400) / 3600);
        var minutes = Math.floor((((seconds % 31536000) % 86400) %  60);
        var second = (((seconds % 31536000) % 86400) % 3600) % 0;         
        var r = (years > 0 ) ? years + " year" + numberEnding(years) : ""; 
        var x = (days > 0) ? days + " day" + numberEnding(days) : "";
        var y = (hours > 0) ? hours + " hour" + numberEnding(hours) : "";
        var z = (minutes > 0) ? minutes + " minute" numberEnding(minutes) : "";
        var u = (second > 0) ? second + " second" + numberEnding(second) : "";
        var str = r + x + y + z + u

        return str
    }
    else {
        return "now"}
    }
}

如何拼湊r xyzu想,如果有兩個以上的最后一個總是分隔and和其余的comma 結果也是string類型。
例如:
“年”,“日”,“小時”,“分鍾”和“秒”
“年”,“日”,“小時”和“分鍾”
“年”
“第二”
“分鍾”和“秒”
它繼續...

我試圖將它們放入array以能夠使用slice() ,但是對於所有可能的組合,它都沒有返回理想的結果。 謝謝

您在使用數組的正確軌道上:

var a = [];
//...push things as you go...
var str = a.length == 1 ? a[0] : a.slice(0, a.length - 1).join(", ") + " and " + a[a.length - 1];

(我個人更喜歡使用牛津逗號[“ this,that,and other”],但是您的示例未使用它,所以這確實符合您的要求...)

現場示例

 test(["this"]); test(["this", "that"]); test(["this", "that", "the other"]); function test(a) { var str = a.length == 1 ? a[0] : a.slice(0, a.length - 1).join(", ") + " and " + a[a.length - 1]; snippet.log("[" + a.join(", ") + "] => " + str); } 
 <!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

暫無
暫無

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

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