将st,nd,rd和th(序号)后缀添加到数字中

Ant*_*lev 118 javascript jquery numbers

我想基于当天动态生成一串文本.所以,例如,如果它是第1天,那么我希望我的代码生成="它的<dynamic> 1*<dynamic string> st </ dynamic string>*</ dynamic>".

共有12天,所以我做了以下几点:

  1. 我已经建立了一个for循环,循环了12天.

  2. 在我的html中,我给了我的元素一个唯一的id来定位它,见下文:

    <h1 id="dynamicTitle" class="CustomFont leftHeading shadow">On The <span></span> <em>of rest of generic text</em></h1>
    
    Run Code Online (Sandbox Code Playgroud)
  3. 然后,在我的for循环中,我有以下代码:

    $("#dynamicTitle span").html(i);
    var day = i;
    if (day == 1) {
        day = i + "st";
    } else if (day == 2) {
        day = i + "nd"
    } else if (day == 3) {
        day = i + "rd"
    }
    
    Run Code Online (Sandbox Code Playgroud)

UPDATE

这是请求的整个for循环:

$(document).ready(function () {
    for (i = 1; i <= 12; i++) {
        var classy = "";
        if (daysTilDate(i + 19) > 0) {
            classy = "future";
            $("#Day" + i).addClass(classy);
            $("#mainHeading").html("");
            $("#title").html("");
            $("#description").html("");
        } else if (daysTilDate(i + 19) < 0) {
            classy = "past";
            $("#Day" + i).addClass(classy);
            $("#title").html("");
            $("#description").html("");
            $("#mainHeading").html("");
            $(".cta").css('display', 'none');
            $("#Day" + i + " .prizeLink").attr("href", "" + i + ".html");
        } else {
            classy = "current";
            $("#Day" + i).addClass(classy);
            $("#title").html(headings[i - 1]);
            $("#description").html(descriptions[i - 1]);
            $(".cta").css('display', 'block');
            $("#dynamicImage").attr("src", ".." + i + ".jpg");
            $("#mainHeading").html("");
            $(".claimPrize").attr("href", "" + i + ".html");
            $("#dynamicTitle span").html(i);
            var day = i;
            if (day == 1) {
                day = i + "st";
            } else if (day == 2) {
                day = i + "nd"
            } else if (day == 3) {
                day = i + "rd"
            } else if (day) {
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Sal*_*n A 305

规则如下:

  • st用于以1结尾的数字(例如,1st,发音为first)
  • nd用于以2结尾的数字(例如92nd,发音为ninety-second)
  • rd用于以3结尾的数字(例如33,发音为第三十三)
  • 作为上述规则的一个例外,所有以11,12或13结尾的"青少年"数字都使用-th(例如,第11,发音第11,第112,发音为100 [和]第12)
  • th用于所有其他数字(例如,第9,发音第9).

以下JavaScript代码(在2014年6月重写)实现了这一点:

function ordinal_suffix_of(i) {
    var j = i % 10,
        k = i % 100;
    if (j == 1 && k != 11) {
        return i + "st";
    }
    if (j == 2 && k != 12) {
        return i + "nd";
    }
    if (j == 3 && k != 13) {
        return i + "rd";
    }
    return i + "th";
}
Run Code Online (Sandbox Code Playgroud)

0-115之间数字的示例输出:

  0  0th
  1  1st
  2  2nd
  3  3rd
  4  4th
  5  5th
  6  6th
  7  7th
  8  8th
  9  9th
 10  10th
 11  11th
 12  12th
 13  13th
 14  14th
 15  15th
 16  16th
 17  17th
 18  18th
 19  19th
 20  20th
 21  21st
 22  22nd
 23  23rd
 24  24th
 25  25th
 26  26th
 27  27th
 28  28th
 29  29th
 30  30th
 31  31st
 32  32nd
 33  33rd
 34  34th
 35  35th
 36  36th
 37  37th
 38  38th
 39  39th
 40  40th
 41  41st
 42  42nd
 43  43rd
 44  44th
 45  45th
 46  46th
 47  47th
 48  48th
 49  49th
 50  50th
 51  51st
 52  52nd
 53  53rd
 54  54th
 55  55th
 56  56th
 57  57th
 58  58th
 59  59th
 60  60th
 61  61st
 62  62nd
 63  63rd
 64  64th
 65  65th
 66  66th
 67  67th
 68  68th
 69  69th
 70  70th
 71  71st
 72  72nd
 73  73rd
 74  74th
 75  75th
 76  76th
 77  77th
 78  78th
 79  79th
 80  80th
 81  81st
 82  82nd
 83  83rd
 84  84th
 85  85th
 86  86th
 87  87th
 88  88th
 89  89th
 90  90th
 91  91st
 92  92nd
 93  93rd
 94  94th
 95  95th
 96  96th
 97  97th
 98  98th
 99  99th
100  100th
101  101st
102  102nd
103  103rd
104  104th
105  105th
106  106th
107  107th
108  108th
109  109th
110  110th
111  111th
112  112th
113  113th
114  114th
115  115th
Run Code Online (Sandbox Code Playgroud)

  • 这不能正确处理三个"青少年"号码的例外情况.例如,数字"111","112"和"113"应分别产生"第111","112"和"第113",_不是"第111","112" "`和``113rd``由当前编码的函数产生. (9认同)
  • 我把它平均化为ES6 lambda,没有任何正当理由:`n => n +(n%10 == 1 && n%100!= 11?'st':n%10 == 2 && n%100!= 12?'nd': N%10 == 3 && N%100 = 13 'RD':!? '日')` (7认同)
  • @Anomaly 很有趣,大约 π/2 年后我仍然可以阅读它。 (5认同)
  • @martineau:好好抓住这一切,回答修改. (3认同)
  • 这个答案似乎已经完美地演变了.谢谢所有贡献者. (3认同)

Fiz*_*han 201

来自Shopify

function getNumberWithOrdinal(n) {
    var s=["th","st","nd","rd"],
    v=n%100;
    return n+(s[(v-20)%10]||s[v]||s[0]);
 }
Run Code Online (Sandbox Code Playgroud)

  • 添加说明可以使它成为更好的答案! (19认同)
  • @Pugazh**A.**找到s [v%10]如果> = 20(20 ... 99th),**B.**如果没有找到,请尝试s [v](0th..3rd),**C.**如果仍未找到,请使用s [0](第4..19) (4认同)
  • 为什么double得到函数名称? (4认同)

Кон*_*Ван 38

Intl.PluralRules标准方法。

我只想在这里放弃执行此操作的规范方式,因为似乎没有人知道。

如果你希望你的代码是

  • 自我记录
  • 容易理解
  • 以现代标准

? 这是要走的路。

const english_ordinal_rules = new Intl.PluralRules("en", {type: "ordinal"});
const suffixes = {
    one: "st",
    two: "nd",
    few: "rd",
    other: "th"
};
function ordinal(number) {
    const suffix = suffixes[english_ordinal_rules.select(number)];
    return (number + suffix);
}

const test = Array(201)
    .fill()
    .map((_, index) => index - 100)
    .map(ordinal)
    .join(" ");
console.log(test);
Run Code Online (Sandbox Code Playgroud)

  • @RobG 我仍然最喜欢这个,部分原因是你可以本地化它。 (2认同)
  • 感谢您分享这个解决方案!喜欢我可以利用预先存在的功能。 (2认同)

Tom*_*aas 35

序数后缀的最小单行方法

function nth(n){return["st","nd","rd"][((n+90)%100-10)%10-1]||"th"}
Run Code Online (Sandbox Code Playgroud)

(这是正整数,见下面的其他变化)

说明

从带有后缀的数组开始["st", "nd", "rd"].我们想要将以1,2,3结尾的整数(但不是以11,12,13结尾)映射到索引0,1,2.

其他整数(包括那些以11,12,13结尾的整数)可以映射到其他任何东西 - 数组中找不到的索引将评估为undefined.这在javascript中是假的,并且使用逻辑或(|| "th")表达式将返回"th"这些整数,这正是我们想要的.

表达式((n + 90) % 100 - 10) % 10 - 1执行映射.打破它:

  • (n + 90) % 100:此表达式采用输入整数 - 10 mod 100,映射10到0,... 99到89,0到90,...,9到99.现在以11,12,13结尾的整数位于较低位置结束(映射到1,2,3).
  • - 10:现在10映射到-10,19到-1,99到79,0到80,... 9到89.以11,12,13结尾的整数映射到负整数(-9,-8, -7).
  • % 10:现在所有以1,2或3结尾的整数都映射到1,2,3.所有其他整数都映射到其他整数(11,12,13仍然映射到-9,-8,-7).
  • - 1:减去一个给出1,2,3的最终映射到0,1,2.

验证它是否有效

function nth(n){return["st","nd","rd"][((n+90)%100-10)%10-1]||"th"}

//test integers from 1 to 124
for(var r = [], i = 1; i < 125; i++) r.push(i + nth(i));

//output result
document.getElementById('result').innerHTML = r.join('<br>');
Run Code Online (Sandbox Code Playgroud)
<div id="result"></div>
Run Code Online (Sandbox Code Playgroud)

变化

允许负整数:

function nth(n){return["st","nd","rd"][(((n<0?-n:n)+90)%100-10)%10-1]||"th"}
Run Code Online (Sandbox Code Playgroud)

在ES6胖箭头语法(匿名函数)中:

n=>["st","nd","rd"][(((n<0?-n:n)+90)%100-10)%10-1]||"th"
Run Code Online (Sandbox Code Playgroud)

更新

表达式是正整数的更短的替代方案

[,'st','nd','rd'][n%100>>3^1&&n%10]||'th'
Run Code Online (Sandbox Code Playgroud)

请参阅此帖子以获得解释.

  • 优雅的。我最喜欢的。 (5认同)
  • 不可读,但我喜欢它! (3认同)

The*_*lis 18

您可以使用矩库本地数据函数

代码:

moment.localeData().ordinal(1)
//1st
Run Code Online (Sandbox Code Playgroud)


Jam*_*iec 7

你只有12天?我很想把它变成一个简单的查找数组:

var suffixes = ['','st','nd','rd','th','th','th','th','th','th','th','th','th'];
Run Code Online (Sandbox Code Playgroud)

然后

var i = 2;
var day = i + suffixes[i]; // result: '2nd'
Run Code Online (Sandbox Code Playgroud)

要么

var i = 8;
var day = i + suffixes[i]; // result: '8th'
Run Code Online (Sandbox Code Playgroud)


小智 7

通过将数字拆分成数组并反转,我们可以使用array[0]和轻松检查数字的最后2位数array[1].

如果一个数字在十几岁,array[1] = 1它需要"th".

function getDaySuffix(num)
{
    var array = ("" + num).split("").reverse(); // E.g. 123 = array("3","2","1")

    if (array[1] != "1") { // Number is in the teens
        switch (array[0]) {
            case "1": return "st";
            case "2": return "nd";
            case "3": return "rd";
        }
    }

    return "th";
}
Run Code Online (Sandbox Code Playgroud)

  • @psx这就是第5行的条件. (2认同)

小智 5

function getSuffix(n) {return n < 11 || n > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((n - 1) % 10, 3)] : 'th'}
Run Code Online (Sandbox Code Playgroud)