在 JavaScript 中为数字添加后缀
javascriptweb developmentfront end technology
问题
我们需要编写一个 JavaScript 函数,以数字 num 作为第一个也是唯一的参数。
我们的函数的任务是将 ‘st’、‘nd’、‘rd’、‘th’ 附加到数字后缀。根据以下规则将数字转换为数字:
- st 与以 1 结尾的数字一起使用(例如 1st,发音为 first)
- nd 与以 2 结尾的数字一起使用(例如 92nd,发音为 ninety-second)
- rd 与以 3 结尾的数字一起使用(例如 33rd,发音为 third-third)
- 作为上述规则的例外,所有"teen"以 11、12 或 13 结尾的数字使用 -th(例如,11th,发音为 eleventh,112th,发音为 one hundred [and] twelfth)
- th 用于所有其他数字(例如,9th,发音为 ninth)。
例如,如果函数的输入是 −
输入
const num = 4513;
输出
const output = '4513th';
输出说明
尽管 4513 以 3 结尾,但 13 是例外情况,必须附加 th
示例
以下是代码 −
const num = 4513; const appendText = (num = 1) => { let suffix = "th"; if (num == 0) suffix = ""; if (num % 10 == 1 && num % 100 != 11) suffix = "st"; if (num % 10 == 2 && num % 100 != 12) suffix = "nd"; if (num % 10 == 3 && num % 100 != 13) suffix = "rd"; return num + suffix; }; console.log(appendText(num));
输出
4513th