🎶 Sym - 一款用 Java 实现的现代化社区(论坛/BBS/社交网络/博客)平台

📕 思源笔记 - 一款桌面端笔记应用,支持 Windows、Mac 和 Linux

🎸 Solo - B3log 分布式社区的博客端节点,欢迎加入下一代社区网络

♏ Vditor - 一款浏览器端的 Markdown 编辑器

JavaScript - 添加序数后缀

2020-05-27

描述

为一个数字添加序数后缀。

提示

  • 使用模运算符(%)获取个位和十位的值
  • 找出匹配的序数后缀
  • 如果模运算结果在 11-19 中,则使用 th

代码

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"
toOrdinalSuffix('113'); // "113th"

返回总目录

每天 30 秒系列之 JavaScript 代码


欢迎注册黑客派社区,开启你的博客之旅。让学习和分享成为一种习惯!

推荐阅读
留下你的脚步