bug 记录 - 内置函数 Date 方法的返回值

发现问题

  • 项目中每次发请求,需要携带一个特殊的请求头,时间戳。格式为 ‘20221011’
  • 原本的代码
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
if(month < 10) {
    month = '0' + month;
};
if(day < 10) {
    day = '0' + day;
};
console.log(year + month + day);
  • 在前 9 个月,代码运行没问题,在进入 10 月后,出现了报错,请求头与后台不匹配,原因是,year,month,day 的类型为 number 类型
var date = new Date('2022/09/09');
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
if(month < 10) {
	// 进入此判断,month 转为 string 类型
    month = '0' + month;
};
if(day < 10) {
    day = '0' + day;
};
console.log(year); // 2022
console.log(month); // '09'
console.log(day); // '09'
// 尽管 year 是 number 类型,与 month 相加后,转成了 string 类型
console.log(year + month + day);// '20220909'
var date = new Date('2022/10/09');
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
if(month < 10) {
	// 未进入此判断,month 还是 number 类型
    month = '0' + month;
};
if(day < 10) {
	// 进入此判断,day 转为 string 类型
    day = '0' + day;
};
console.log(year); // 2022
console.log(month); // 10
console.log(day); // '09'
// 尽管 day 为 string 类型,但是前面的 year 与 month 都是 number 类型,已经进行了数学相加
console.log(year + month + day); // '203209'
  • 因此在未用特殊符号进行拼接时,需要考虑到返回值的类型问题
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值