213

現在の日付に基づいてテキストの文字列を動的に生成したいと思います。したがって、たとえば、1 日目の場合、コードで = "Its the <dynamic>1*<dynamic string> st </dynamic string>*</dynamic>" を生成する必要があります。

全部で 12 日間あるので、次のことを行いました。

  1. 12 日間ループする for ループを設定しました。

  2. 私のhtmlでは、要素をターゲットにするための一意のIDを要素に与えました。以下を参照してください。

    <h1 id="dynamicTitle" class="CustomFont leftHeading shadow">On The <span></span> <em>of rest of generic text</em></h1>
    
  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"
    }
    

アップデート

これは、要求された 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) {
            }
        }
    }
4

22 に答える 22

451

ルールは次のとおりです。

  • st は 1 で終わる数字で使用されます (例: 1st、最初に発音)
  • nd は 2 で終わる数字で使用されます (例: 92nd、92 と発音)
  • rd は 3 で終わる数字で使用されます (例: 33rd、33 と発音)
  • 上記のルールの例外として、11、12、または 13 で終わるすべての「10 代」の数字は -th を使用します (たとえば、11th は 11th と発音し、112th は 100 と発音し、12th と発音します)。
  • th は他のすべての数字に使用されます (例: 9th、発音は 9th)。

次の 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";
}

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
于 2012-11-29T14:09:18.343 に答える
236

Shopifyから

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

[-4,-1,0,1,2,3,4,10,11,12,13,14,20,21,22,100,101,111].forEach(
  n => console.log(n + ' -> ' + getNumberWithOrdinal(n))
);

于 2015-07-24T16:38:16.473 に答える
87

序数接尾辞の最小限の 1 行アプローチ

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

(これは正の整数用です。他のバリエーションについては以下を参照してください)

説明

接尾辞 の配列から始めます["st", "nd", "rd"]。1、2、3 で終わる (11、12、13 で終わらない) 整数をインデックス 0、1、2 にマップします。

他の整数 (11、12、13 で終わるものを含む) は、他のものにマップできます。配列内に見つからないインデックスは、 に評価されundefinedます。これは javascript では誤りであり、論理 or ( || "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 で終わる整数は下位にあります。 end (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 を引くと、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>');
<div id="result"></div>

バリエーション

負の整数を許可:

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

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

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

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

ES6 の太い矢印の構文 (無名関数) では:

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

アップデート

正の整数のさらに短い代替は、次の式です。

[,'st','nd','rd'][n%100>>3^1&&n%10]||'th'

説明については、この投稿を参照してください。

更新 2

[,'st','nd','rd'][n/10%10^1&&n%10]||'th'
于 2016-09-13T09:15:25.203 に答える
48

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);

于 2019-08-16T03:50:44.903 に答える
7

12日しかないの?単純なルックアップ配列にしたくなるでしょう:

var suffixes = ['','st','nd','rd','th','th','th','th','th','th','th','th','th'];

それから

var i = 2;
var day = i + suffixes[i]; // result: '2nd'

また

var i = 8;
var day = i + suffixes[i]; // result: '8th'
于 2012-11-29T14:09:22.290 に答える
4
function getSuffix(n) {return n < 11 || n > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((n - 1) % 10, 3)] : 'th'}
于 2014-05-14T06:29:26.017 に答える
3

この問題を解決するためにこの関数を書きました:

// this is for adding the ordinal suffix, turning 1, 2 and 3 into 1st, 2nd and 3rd
Number.prototype.addSuffix=function(){
    var n=this.toString().split('.')[0];
    var lastDigits=n.substring(n.length-2);
    //add exception just for 11, 12 and 13
    if(lastDigits==='11' || lastDigits==='12' || lastDigits==='13'){
        return this+'th';
    }
    switch(n.substring(n.length-1)){
        case '1': return this+'st';
        case '2': return this+'nd';
        case '3': return this+'rd';
        default : return this+'th';
    }
};

これを使用すると、任意の数に入れるだけ.addSuffix()で、必要な結果が得られます。例えば:

var number=1234;
console.log(number.addSuffix());
// console will show: 1234th
于 2013-09-20T11:39:00.843 に答える
1

先日、この単純な関数を書きました。日付には大きな数字は必要ありませんが、これはより高い値にも対応します (1013th、36021st など...)。

var fGetSuffix = function(nPos){

    var sSuffix = "";

    switch (nPos % 10){
        case 1:
            sSuffix = (nPos % 100 === 11) ? "th" : "st";
            break;
        case 2:
            sSuffix = (nPos % 100 === 12) ? "th" : "nd";
            break;
        case 3:
            sSuffix = (nPos % 100 === 13) ? "th" : "rd";
            break;
        default:
            sSuffix = "th";
            break;
    }

    return sSuffix;
};
于 2013-07-24T15:11:35.717 に答える
-1

とても読みやすくてわかりやすいのでオススメです。それが役立つことを願っていますか?

  • 負の整数、つまり 1 未満の数値の使用を避け、false を返します。
  • 入力が 0 の場合は 0 を返します
function numberToOrdinal(n) {

  let result;

  if(n < 0){
    return false;
  }else if(n === 0){
    result = "0";
  }else if(n > 0){

    let nToString = n.toString();
    let lastStringIndex = nToString.length-1;
    let lastStringElement = nToString[lastStringIndex];

    if( lastStringElement == "1" && n % 100 !== 11 ){
      result = nToString + "st";
    }else if( lastStringElement == "2" && n % 100 !== 12 ){
      result = nToString + "nd";
    }else if( lastStringElement == "3" && n % 100 !== 13 ){
      result = nToString + "rd";
    }else{
      result = nToString + "th";
    }

  }

  return result;
}

console.log(numberToOrdinal(-111));
console.log(numberToOrdinal(0));
console.log(numberToOrdinal(11));
console.log(numberToOrdinal(15));
console.log(numberToOrdinal(21));
console.log(numberToOrdinal(32));
console.log(numberToOrdinal(43));
console.log(numberToOrdinal(70));
console.log(numberToOrdinal(111));
console.log(numberToOrdinal(300));
console.log(numberToOrdinal(101));

出力

false
0
11th
15th
21st
32nd
43rd
70th
111th
300th
101st
于 2019-01-31T12:12:05.037 に答える
-7

<p>31<sup>st</sup> March 2015</p>

使用できます

1<sup>st</sup> 2<sup>nd</sup> 3<sup>rd</sup> 4<sup>th</sup>

サフィックスの配置用

于 2015-03-26T06:08:29.790 に答える