用js实现六十甲子
六十甲子是中国传统历法中的干支纪年系统,由天干(10个)与地支(12个)循环组合而成,共60种组合。以下是使用JavaScript生成六十甲子的实现方法:
定义天干和地支数组
天干和地支需要预先定义,并按顺序组合:

const heavenlyStems = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'];
const earthlyBranches = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
生成六十甲子列表
通过循环将天干与地支按顺序配对,注意天干和地支的循环周期不同(10和12的最小公倍数为60):

function generateSexagenaryCycle() {
const cycle = [];
for (let i = 0; i < 60; i++) {
const stemIndex = i % heavenlyStems.length;
const branchIndex = i % earthlyBranches.length;
cycle.push(heavenlyStems[stemIndex] + earthlyBranches[branchIndex]);
}
return cycle;
}
const sexagenaryCycle = generateSexagenaryCycle();
console.log(sexagenaryCycle); // 输出完整的六十甲子数组
根据年份或索引获取对应干支
若需根据特定年份或索引获取干支组合(如2023年为癸卯年),可扩展功能:
function getStemBranchByYear(year) {
// 已知2020年为庚子年(索引36,因六十甲子循环从0开始)
const baseYear = 2020;
const baseIndex = 36;
const offset = (year - baseYear) % 60;
const index = (baseIndex + offset + 60) % 60; // 处理负数
return sexagenaryCycle[index];
}
console.log(getStemBranchByYear(2023)); // 输出 "癸卯"
处理负年份或超出范围的情况
若需支持农历或历史年份,需确保索引计算正确:
function normalizeIndex(index) {
return ((index % 60) + 60) % 60; // 保证结果在0-59之间
}
输出示例
运行上述代码后,生成的六十甲子列表前5项为:['甲子', '乙丑', '丙寅', '丁卯', '戊辰', ...]
通过调用getStemBranchByYear(2023)可得到当前年份的干支组合“癸卯”。






