You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何创建以字母为标题的按字母排序货币列表?

嘿,我完全get到你想要的效果啦——就是那种按字母顺序分组,每个字母作为独立标题,下面列出对应首字母的货币列表对吧?其实不用费劲找什么复杂的开发包,不管是静态写还是动态生成都很容易实现,我给你两种实用方案:

方案一:静态Markdown实现(适合文档/笔记场景)

这种方式最简单直接,不需要任何工具,直接用Markdown的二级标题+无序列表就能搞定,效果完全符合你的需求:

## A
- 阿富汗尼(AFN)
- 阿尔巴尼亚列克(ALL)
- 安哥拉宽扎(AOA)

## B
- 巴哈马元(BSD)
- 巴林第纳尔(BHD)
- 巴巴多斯元(BBD)

## C
- 加拿大元(CAD)
- 人民币(CNY)
- 智利比索(CLP)

渲染出来就是每个字母作为标题,下面对应同首字母的货币列表,和你想要的效果一致。

方案二:动态前端实现(适合网页自动生成)

如果你的需求是在网页里自动从数据源生成这个列表,那几行JavaScript代码就能搞定,不用依赖复杂的库:

步骤1:准备货币数据

先整理好你的货币数组,包含名称和代码:

const currencies = [
  { name: '阿富汗尼', code: 'AFN' },
  { name: '阿尔巴尼亚列克', code: 'ALL' },
  { name: '安哥拉宽扎', code: 'AOA' },
  { name: '巴哈马元', code: 'BSD' },
  { name: '巴林第纳尔', code: 'BHD' },
  { name: '加拿大元', code: 'CAD' },
  { name: '人民币', code: 'CNY' }
];

步骤2:按首字母分组并排序

reduce方法把货币按首字母分组,再对字母排序:

// 按首字母分组(英文名称直接取首字母,中文需要转拼音,后面会说)
const groupedCurrencies = currencies.reduce((groups, currency) => {
  // 这里以英文名称为例,取首字母并转大写
  const firstLetter = currency.name.charAt(0).toUpperCase();
  if (!groups[firstLetter]) {
    groups[firstLetter] = [];
  }
  groups[firstLetter].push(currency);
  return groups;
}, {});

// 对字母标题按顺序排序
const sortedLetters = Object.keys(groupedCurrencies).sort();

步骤3:渲染到页面

把分组好的内容动态插入到HTML容器里:

const container = document.getElementById('currency-list');
sortedLetters.forEach(letter => {
  // 创建字母标题
  const heading = document.createElement('h2');
  heading.textContent = letter;
  container.appendChild(heading);
  
  // 创建货币列表
  const list = document.createElement('ul');
  groupedCurrencies[letter].forEach(currency => {
    const listItem = document.createElement('li');
    listItem.textContent = `${currency.name}(${currency.code})`;
    list.appendChild(listItem);
  });
  container.appendChild(list);
});

补充:中文货币按拼音首字母排序

如果你的货币是中文名称,需要按拼音首字母分组的话,可以用轻量的拼音转换工具(比如pinyin-pro),修改首字母获取的代码:

import { pinyin } from 'pinyin-pro';

// ...
const firstLetter = pinyin(currency.name, { pattern: 'first', type: 'uppercase' })[0];
// ...

这样就能自动把中文货币按拼音首字母分组排序啦。

内容的提问来源于stack exchange,提问作者user10004335

火山引擎 最新活动