是否有 JavaScript 代码片段可以将 1-31 的值转换为 1st、2nd、3rd 等?
Is there a JavaScript code snippet to take a value of 1-31 and convert it to 1st, 2nd, 3rd, etc?
谢谢!
function getOrdinal(n) {
var s=["th","st","nd","rd"],
v=n%100;
return n+(s[(v-20)%10]||s[v]||s[0]);
}
感谢@RobG位修改版
Thanks @RobG bit modified version
function getOrdinal(n) {
if((parseFloat(n) == parseInt(n)) && !isNaN(n)){
var s=["th","st","nd","rd"],
v=n%100;
return n+(s[(v-20)%10]||s[v]||s[0]);
}
return n;
}
测试
getOrdinal("test"); // test
getOrdinal(1.5); // 1.5
getOrdinal(1); // 1st
getOrdinal(2); // 2nd
getOrdinal(3); // 3rd
getOrdinal(4); // 4th
getOrdinal(true); // true
getOrdinal(Infinity); // Infinity
getOrdinal(NaN); // NaN
getOrdinal(void 0); // undefined
这篇关于取值 1-31 并将其转换为带有 JavaScript 的序号日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!