javascript中的序数
有没有什么优雅的方法可以在 js/coffee 中获取 word 格式的序数?像这样的:
Is there any elegant way how to get ordinals in word format in js/coffee? Something like this:
ordinalInWord(1) # => "first"
ordinalInWord(2) # => "second"
ordinalInWord(5) # => "fifth"
推荐答案
恐怕序数不够规则,无法避免将它们逐个打出来.
I'm afraid the ordinals aren't regular enough to avoid typing each of them out.
function ordinalInWord( cardinal ) {
var ordinals = [ 'zeroth', 'first', 'second', 'third' /* and so on */ ];
return ordinals[ cardinal ];
}
如果您需要该功能在 20 岁以后工作,您可以利用出现的模式:
If you need the function work past 20, you can take advantage of the pattern that emerges:
function ordinalInWord( cardinal ) {
var ordinals = [ 'zeroth', 'first', 'second', 'third' /* and so on up to "twentieth" */ ];
var tens = {
20: 'twenty',
30: 'thirty',
40: 'forty' /* and so on up to 90 */
};
var ordinalTens = {
30: 'thirtieth',
40: 'fortieth',
50: 'fiftieth' /* and so on */
};
if( cardinal <= 20 ) {
return ordinals[ cardinal ];
}
if( cardinal % 10 === 0 ) {
return ordinalTens[ cardinal ];
}
return tens[ cardinal - ( cardinal % 10 ) ] + ordinals[ cardinal % 10 ];
}
演示:http://jsfiddle.net/AQCqK/
将其扩展到超过 99 应该不难.
Expanding that to work past 99 shouldn't be difficult.
相关文章