JS实用小方法-通过身份证号获取年龄或性别

604 阅读1分钟

一、代码注释详解

参数解析

  • cardID参数为身份证号,字符串类型,数字类型传入之前必须转换字符串,否则会出现精度问题,合法参数:18位标准身份证号
  • flag控制是年龄或性别,字符类类型,默认age,合法参数:age sex

代码注释

function leGetAge(cardID, flag = 'age') {
  // 获取当前年月日
  let currentYear = new Date().getFullYear();
  let currentMonth = new Date().getMonth() + 1;
  // 提前转为字符串 用于判定日期是否需要补零
  let currentDay = new Date().getDate() + '';
  let currentMonthDay = `${ currentMonth }${ currentDay.length < 2 ? '0' + currentDay : currentDay }`;
  // window.location.href = "https://juejin.cn/user/84036866547575"
  // 截取年 月日
  let year = cardID.slice(6, 10);
  let monthDay = cardID.slice(10, 14);
  // 计算当前年减去出生年份
  let birthdayCount = currentYear - year;
  // 年龄or性别
  if(flag === 'age') {
    // 判断是否过了生日 (此处依据:过了生日第二天起为+1岁)
    return Number(monthDay) < Number(currentMonthDay)  ? birthdayCount : birthdayCount - 1;
  }
  else {
    // 判断第17位奇偶数  奇男偶女
    return cardID[16] % 2 === 0 ? '女' : '男';
  }
}
console.log(leGetAge('110101199810185215', 'age'));
console.log(leGetAge('110101199810185215', 'sex'));