Javascript 序数:将 st、nd、rd 和 th 后缀添加到数字中

2022/11/7 1:24:01

本文主要是介绍Javascript 序数:将 st、nd、rd 和 th 后缀添加到数字中,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

在Javascript中,通常被认为是处理绝对数字的最佳实践,因为绝对数字是一种定义的类型。但是,在用户界面中表示这些数字时,我们更有可能希望以不同的方式表达它们。例如,假设我有以下数字列表。我仍然想将它们存储为数字,但随后添加,,,或者在向用户显示它们时:numberndstrdth

let x = [ 1, 13, 22, 100, 1204, 133 ];

我当然可以手动执行此操作,并存储特定前缀的每个数字,或定义自定义规则,但这有点混乱 - 如果我需要支持多种语言怎么办。虽然在英语中我们写给代表的地方,但在其他语言中可能不一样。3rd3rd

幸运的是,Javascript中有一个解决方案-使用。这将根据区域设置定义复数规则:Intl.PluralRules

let plurals = Intl.PluralRules();
let x = plurals.select(0) // Returns "other"
let y = plurals.select(1) // Returns "one"
let z = plurals.select(2) // Returns "other"

默认情况下,配置为,这意味着任何大于 1 的内容都被视为复数。上面,如您所见,让我们区分一个数字是否是复数。PluralRulescardinalPluralRules

当我们将其设置为时,事情会变得更加有趣,这考虑到了我们使用数字的方式。在这里,它将告诉我们如何处理每个数字的特定语言规则 - 因此我们可以做一些事情,例如,和ordinal2nd3rd4th

const plurals = new Intl.PluralRules('en-US', { type: 'ordinal' });
let a = plurals.select(0); // Returns "other"
let b = plurals.select(1); // Returns "one"
let c = plurals.select(2); // Returns "two"
let d = plurals.select(3); // Returns "few"
let e = plurals.select(4); // Returns "other"

现在我们可以根据区域设置自定义输出,这样我们就不会遇到奇怪的问题。在这里,我们使用,但任何其他有效的区域设置也可以使用。要将我们的数字映射到,,,等,我们只需要创建一个这样的映射:en-US1st2nd3rd

let x = [ 1, 13, 22, 100, 1204, 133 ];

const plurals = new Intl.PluralRules('en-US', { type: 'ordinal' });

let pluralMapping = {
    "one" : "st",
    "two" : "nd",
    "few" : "rd",
    "other" : "th"
}

let y = [];
x.forEach((item) => {
    let getPlural = plurals.select(item);
    let pluralEnding = pluralMapping[getPlural]
    y.push(`${item}${pluralEnding}`)
})

console.log(y); // ['1st', '13th', '22nd', '100th', '1204th', '133rd']


这篇关于Javascript 序数:将 st、nd、rd 和 th 后缀添加到数字中的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程