📅  最后修改于: 2023-12-03 15:23:24.925000             🧑  作者: Mango
在JS中,有时需要为数字添加位置后缀,例如添加 "st"、 "nd"、 "rd"、 "th" 等后缀来表示排名或序号。本文提供了一些JS代码示例,用于在数字后添加位置后缀。
使用 if 语句是添加位置后缀的最基本方法。例如,以下代码会根据数字的个位数来添加相应的位置后缀:
function addSuffix(number) {
var suffix;
if (number % 10 === 1 && number % 100 !== 11) {
suffix = "st";
} else if (number % 10 === 2 && number % 100 !== 12) {
suffix = "nd";
} else if (number % 10 === 3 && number % 100 !== 13) {
suffix = "rd";
} else {
suffix = "th";
}
return number + suffix;
}
console.log(addSuffix(1)); // 输出:1st
console.log(addSuffix(2)); // 输出:2nd
console.log(addSuffix(3)); // 输出:3rd
console.log(addSuffix(11)); // 输出:11th
console.log(addSuffix(20)); // 输出:20th
console.log(addSuffix(21)); // 输出:21st
使用数组可以使代码更加简洁。以下是使用数组的示例:
function addSuffix(number) {
var suffixes = ["th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"],
suffix = (number % 100 >= 11 && number % 100 <= 13) ? "th" : suffixes[number % 10];
return number + suffix;
}
console.log(addSuffix(1)); // 输出:1st
console.log(addSuffix(2)); // 输出:2nd
console.log(addSuffix(3)); // 输出:3rd
console.log(addSuffix(11)); // 输出:11th
console.log(addSuffix(20)); // 输出:20th
console.log(addSuffix(21)); // 输出:21st
在这个例子中,suffixes
数组保存了所有可能出现的后缀。根据个位数的不同,通过 number % 10
来选择合适的后缀。
除了自己实现这个函数,也可以使用一些第三方库来实现该功能。其中一个常用的库是 numeral.js。
numeral(1).format('0o'); // 1st
numeral(2).format('0o'); // 2nd
numeral(3).format('0o'); // 3rd
numeral(11).format('0o'); // 11th
numeral(20).format('0o'); // 20th
numeral(21).format('0o'); // 21st
使用上述代码,需要先下载 numeral.js
并在HTML中引入相关文件。
以上是在JS中为数字添加位置后缀的几种实现方式。使用函数可以帮助我们更快速地处理业务需求。