JavaScript中向數字新增字尾
問題
我們需要編寫一個 JavaScript 函式,它採用一個數字 num 作為第一個也是唯一一個引數。
我們的函式的任務是根據以下規則將“st”、“nd”、“rd”、“th”附加到數字
- st 用於以 1 結尾的數字(例如 1st,讀作 first)
- nd 用於以 2 結尾的數字(例如 92nd,讀作 ninety-second)
- rd 用於以 3 結尾的數字(例如 33rd,讀作 thirty-third)
- 作為上述規則的例外,所有以 11、12 或 13 結尾的“teen”數字都使用 - th(例如 11th,讀作 eleventh,112th,讀作 one hundred [and] twelfth)
- th 用於所有其他數字(例如 9th,讀作 ninth)。
例如,如果輸入函式的是 -
輸入
const num = 4513;
輸出
const output = '4513th';
輸出說明
即使以 4513 結尾,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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP