在不少业务场景中,比如月度报表切换、生日提醒、账单周期选择,我们都希望界面上的月份列表能把“当前月”排在第一位,后面再按自然顺序列出其他月份。用JavaScript处理这类需求并不复杂,关键在于利用数组的截取与拼接。

基本思路
月份通常用 0 到 11 的数字表示(对应一月到十二月)。假设我们有一个按自然顺序排好的月份数组,只要知道当前月索引,就可以把数组从当前月位置“断开”,前半段移到末尾,从而实现当前月置顶。
示例数据
我们先准备一个月份名称数组,并获取当前月份:
// 月份名称列表
const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月',
'七月', '八月', '九月', '十月', '十一月', '十二月'];
// 获取当前月份索引(0-11)
const currentMonth = new Date().getMonth();
console.log('当前月份索引:', currentMonth);
实现当前月优先的排序函数
下面封装一个函数,接收月份数组和当前月索引,返回调整后的新数组:
function sortMonthsCurrentFirst(months, current) {
// 当前月及之后的部分
const front = months.slice(current);
// 当前月之前的部分
const behind = months.slice(0, current);
// 拼接:当前月优先,前面月份补在后面
return front.concat(behind);
}
const sorted = sortMonthsCurrentFirst(monthNames, currentMonth);
console.log('调整后顺序:', sorted);
直接使用数字月份
如果原始数据就是数字月份,同样适用:
const numMonths = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
const sortedNum = sortMonthsCurrentFirst(numMonths, currentMonth);
console.log('数字月份调整:', sortedNum);
在页面中渲染
得到排序后的数组后,可以很轻松地渲染成下拉框或列表:
const select = document.createElement('select');
sorted.forEach(function (m, idx) {
const opt = document.createElement('option');
opt.value = idx;
opt.textContent = m;
select.appendChild(opt);
});
document.body.appendChild(select);
小结
通过 slice 与 concat 的组合,我们无需复杂循环即可完成月份动态置顶。这种方法时间复杂度为 O(n),简单清晰,也方便抽成公共工具函数在多个页面复用。
JavaScript月份排序数组排序修改时间:2026-07-27 00:48:16