Maison  >  Article  >  interface Web  >  JavaScript趣题:这是哪个世纪?

JavaScript趣题:这是哪个世纪?

黄舟
黄舟original
2017-02-04 15:15:461352parcourir

输入一些用数字表示的年份,返回它们所属的是哪一个世纪。

例如2016年,毫无疑问,这是第21世纪,我们记作21st。

这些年份都是4位的数字字符串,所以无需你对它做校验。

下面,是一些例子:

Input: 1999 Output: 20th  
Input: 2011 Output: 21st  
Input: 2154 Output: 22nd  
Input: 2259 Output: 23rd  
Input: 1124 Output: 12th  
Input: 2000 Output: 20th

首先,咋们观察一下,怎么把年份转化为世纪?


略作思索,便可以想到,先把年份除以100,再向上取整,就可以得到所属的世纪。

但是,还有一个问题,世纪后面的那个“st”,“nd”,“rd”,“th”该怎么弄呢?

咋们拿只笔,拿张白纸,统计一下,便可以发现规律:

20世纪及以前,比如说:tenth,eleventh,twelfth......twentieth都是加th。

20世纪以后,凡是被10整除得1的世纪,比如twentyfirst,thirtyfirst,fortyfirst......都是加st,凡是被10整除得2的世纪,则是加nd,凡是被10整除得3的世纪,加rd。

而20世纪以后的其他世纪,都是加th。

于是,我们把这统计的逻辑写成代码:

function whatCentury(year){  
    var century = Math.ceil(year / 100);  
    if(century <= 20){  
        century += "th";  
    }  
    else{  
        if(century % 10 == 1){  
            century += "st";  
        }  
        else if(century % 10 == 2){  
            century += "nd";  
        }  
        else if(century % 10 == 3){  
            century += "rd";  
        }  
        else{  
            century += "th";  
        }  
    }  
    return century;  
}

以上就是 JavaScript趣题:这是哪个世纪?的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn