Javascript中的单数和复数单词?

Javascript中的单数和复数单词?,javascript,jquery,html,Javascript,Jquery,Html,这是我用于Javascript倒计时的代码: <script type="text/javascript"> function ShowTimes1() { var now = new Date(); if (now.getHours() < 6) { newVar = 5 } else if (now.getHours() < 12) { newVar = 11 } else if (now.getHour

这是我用于Javascript倒计时的代码:

<script type="text/javascript">
function ShowTimes1() {
    var now = new Date();
    if (now.getHours() < 6) {
        newVar = 5
    } else if (now.getHours() < 12) {
        newVar = 11
    } else if (now.getHours() < 18) {
        newVar = 17
    } else {
        newVar = 23
    }
    var hrs = newVar - now.getHours();
    var mins = 59 - now.getMinutes();
    var secs = 59 - now.getSeconds();
    var str = '';
    str += '<b><a href="discount.php" style="text-decoration:none;cursor:default;"><span style="color:#FF9600;">Limited Time Offer!</span> <span style="color:#489FDC;">' + hrs + ' Hours ' + mins + ' Minutes ' + secs + ' Seconds</span></a></b>';
    document.getElementById('countdownToMidnight').innerHTML = str
}
var _cntDown;

function StopTimes() {
    clearInterval(_cntDown)
}
</script>

有没有简单的方法来修复我的代码以实现这一点?

使用
三元运算符来简化您的工作

试试看

全行代码:

str += '<b><a href="discount.php" style="text-decoration:none;cursor:default;"><span style="color:#FF9600;">Limited Time Offer!</span> <span style="color:#489FDC;">'+ hrs +' Hour' + ((hrs>1)?'s':'') +mins+' Minute' + ((mins>1)?'s':'') +secs+' Second' + ((secs>1)?'s':'')+ ' Seconds</span></a></b>';
str+='';

'+hrs+'Hours'+mins+'Minutes'+secs+'秒 成为

// ...
' + hrs + ' Hour' + (1===hrs) ? ' ' : 's ' 
 + mins + ' Minute' + (1===mins) ? ' ' : 's ' 
 + secs + ' Second' +  (1===secs) ? ' ' : 's' 
// ...

对于这种简单的情况,可以使用三元运算符。但是,它将不适用于多种语言,并且将很难翻译您的应用程序

为了解决这样的用例,我实现了一个小型库,可用于在JavaScript中对单词进行复数。它透明地将CLDR数据库用于多个地区,因此它几乎支持您想要使用的任何语言。它的API非常简约,集成非常简单。我叫它-

这里有一篇关于它的介绍性小文章:«»


您可以在项目中随意使用它。我也将很高兴收到您的反馈

刚刚尝试过,但是倒数计时器就从页面上消失了:/@user2970202合并时你应该错过了一些东西。只需尝试更新的代码。@user2970202然后尝试将条件从
hrs>1
更改为
hrs===1
尝试了这一点,它只会再次显示结尾处带有
s
的每个。这就是我目前拥有的:
++hrs+'Hour'+((hrs===1)?:'')+min+'Minute'+((min==1)?s':'')+secs+'Second'+((secs==1)?s':'')+
@user2970202像这样试试
((hrs==1)?:'')
str += '<b><a href="discount.php" style="text-decoration:none;cursor:default;"><span style="color:#FF9600;">Limited Time Offer!</span> <span style="color:#489FDC;">'+ hrs +' Hour' + ((hrs>1)?'s':'') +mins+' Minute' + ((mins>1)?'s':'') +secs+' Second' + ((secs>1)?'s':'')+ ' Seconds</span></a></b>';
// ...
' + hrs + ' Hour' + (1===hrs) ? ' ' : 's ' 
 + mins + ' Minute' + (1===mins) ? ' ' : 's ' 
 + secs + ' Second' +  (1===secs) ? ' ' : 's' 
// ...