<万博manbetx平台> 数字序号的后缀 toOrdinalSuffix – JavaScript 实用代码片段-万博manbetx平台

数字序号的后缀 toOrdinalSuffix – JavaScript 实用代码片段

为数字添加序号后缀。

使用模运算符(%)来查找各位和十位的值。查找哪些序号模式数字匹配。如果数字在十位模式中找到,请使用十位的序数。

const toOrdinalSuffix = num => {
  const int = parseInt(num),
    digits = [int % 10, int % 100],
    ordinals = ['st', 'nd', 'rd', 'th'],
    oPattern = [1, 2, 3, 4],
    tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19];
  return oPattern.includes(digits[0]) && !tPattern.includes(digits[1])
    ? int + ordinals[digits[0] - 1]
    : int + ordinals[3];
};
toOrdinalSuffix('123'); // "123rd"

更多代码 JavaScript 实用代码片段 请查看 https://www.762w6o.com/30-seconds-of-code/

赞(0) 打赏
未经允许不得转载:万博manbetx平台 » 数字序号的后缀 toOrdinalSuffix – JavaScript 实用代码片段

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏