gpt4 book ai didi

javascript - 根据项目索引附加序号后缀 ('-st' , '-nd' , '-rd' , '-th' )

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:29:20 25 4
gpt4 key购买 nike

比如,我有一个选项值数组,例如:

var arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

我需要将其转换为格式化字符串数组,例如:

var result = ['1-st option is "a"', '2-nd option is "b", '3-rd option is "c"', '4-th option is "d"',...];

我设法实现了其中的大部分:

var result = [];
for(var i = 0; i < arr.length; i++){
result.push((i+1)+' option is "'+arr[i]+'"');
}

它生成字符串,比如 1 option is "a",等等。但我似乎无法处理这些后缀('-st'、'-nd'、'-rd'、'-th')。大佬们能帮我解决一下这个问题吗?谢谢!

最佳答案

您可以将必要的后缀放入数组中并选择与您的索引相对应的一个:

const arr = [...'abcdefghijklmnopqrstuvwxyz'];
const suffixes = ['th', 'st', 'nd', 'rd'];

const result = arr.map((item, i) =>
(idx = ~~(i % 10) + 1 > 3 || ~~(i / 10) == 1 ? 0 : ~~(i % 10) + 1,
`${i+1}-${suffixes[idx]} options is '${item}'`));

console.log(result);
.as-console-wrapper {min-width: 100%}

关于javascript - 根据项目索引附加序号后缀 ('-st' , '-nd' , '-rd' , '-th' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57079172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com