用js实现六十甲子


六十甲子是中国传统的干支纪年法,由天干(10个)和地支(12个)组合而成,共60种组合。以下是使用JavaScript生成六十甲子的实现方法:
天干地支数组定义
const heavenlyStems = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'];
const earthlyBranches = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
生成六十甲子数组
function generateSexagenaryCycle() {
const cycle = [];
for (let i = 0; i < 60; i++) {
const stemIndex = i % 10;
const branchIndex = i % 12;
cycle.push(heavenlyStems[stemIndex] + earthlyBranches[branchIndex]);
}
return cycle;
}
按顺序输出六十甲子
const sexagenaryCycle = generateSexagenaryCycle();
console.log(sexagenaryCycle);
// 输出: ["甲子", "乙丑", "丙寅", ..., "癸亥"]
根据年份获取对应干支
function getYearStemBranch(year) {
// 以1984年为甲子年基准(1984 % 60 = 4,对应甲子)
const offset = (year - 1984) % 60;
// 处理负数情况
const index = offset >= 0 ? offset : 60 + offset;
return sexagenaryCycle[index];
}
示例用法
console.log(getYearStemBranch(2023)); // 输出: "癸卯"
console.log(getYearStemBranch(2000)); // 输出: "庚辰"
该方法完整实现了六十甲子的生成和查询功能,可以直接在浏览器或Node.js环境中运行。干支组合的算法基于模运算,确保60年循环的正确性。






