2015-09-04 59 views
2

我有這個function人類可讀的持續時間。人類可讀時間的格式? JavaScript

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"} 
    } 
} 

如何放在一起rxyzu一樣,如果有兩個以上的最後一個總是and分隔和comma休息。結果也是string類型。
例如:
「年」, 「日」, 「小時」, 「分」 和 「秒」
「年」, 「日」, 「小時」 和 「分」
「年」
「第二個」
‘分’和‘秒’
如此下去......

我試圖把它們放進一個array能夠使用slice(),但它不會返回所有可能組合的理想的結果。 感謝

回答

4

你是在正確的軌道與陣列上:

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]; 

(我個人更喜歡牛津逗號[「這個,那個,和其他」],但你的例子並不使用它,所以這確實你問什麼,而不是...)

活生生的例子

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>

相關問題