在PHP,求这个月,上个月,上两月是很简单的,有现成的方法给你。
$data['month']=array(date('Y-m'),date('Y-m', strtotime('-1 month')),date('Y-m', strtotime('-2 month'))); 现在需要在JS上做。请求只返回了本月,根据本月求上月和上两月。逻辑是很简单,无非就是月份小于十,加个前导零;月份小于1,就变成12月,年份再减一。但我写出来的代码就是很丑……我要勇敢地记下我写的丑样代码:
success: function (response) {
if (response.errcode == 0) {
var intYear = parseInt(response.data['year']);
var intMonth = parseInt(response.data['month']);
var thisMonth = "";
var lastMonth = "";
var lastTwoMonths = "";
if (2 < intMonth < 9) {
thisMonth = intYear + "-" + "0" + intMonth;
lastMonth = intYear + "-" + "0" + (intMonth - 1);
lastTwoMonths = intYear + "-" + "0" + (intMonth - 2);
}
switch (intMonth) {
case 1:
thisMonth = intYear + "-" + "01";
lastMonth = (intYear - 1) + "-" + "12";
lastTwoMonths = (intYear - 1) + "-" + "11";
break;
case 2:
thisMonth = intYear + "-" + "02";
lastMonth = intYear + "-" + "01";
lastTwoMonths = (intYear - 1) + "-" + "12";
break;
case 9:
thisMonth = intYear + "-" + "09";
lastMonth = intYear + "-" + "08";
lastTwoMonths = intYear + "-" + "07";
break;
case 10:
thisMonth = intYear + "-" + intMonth;
lastMonth = intYear + "-" + "09";
lastTwoMonths = intYear + "-" + "08";
break;
case 11:
thisMonth = intYear + "-" + intMonth;
lastMonth = intYear + "-" + "10";
lastTwoMonths = intYear + "-" + "09";
break;
}
我是真的想了很久,但是写出来真的觉得很丑,于是拿给老大叫他帮改一下,结果瞬间高富帅了。
success: function (response) {
if (response.errcode == 0) {
var tempYear = parseInt(response.data['year']);
var tempMonth = parseInt(response.data['month']);
var thisMonth = tempYear + "-" + (tempMonth >= 10 ? tempMonth : "0" + tempMonth);
if (tempMonth == 1) {
tempYear--;
tempMonth = 12;
} else {
tempMonth--;
}
var lastMonth = tempYear + "-" + (tempMonth >= 10 ? tempMonth : "0" + tempMonth);
if (tempMonth == 1) {
tempYear--;
tempMonth = 12;
} else {
tempMonth--;
}
var lastTwoMonths = tempYear + "-" + (tempMonth >= 10 ? tempMonth : "0" + tempMonth);
$("#this-month-td").text(thisMonth);
$("#last-month-td").text(lastMonth);
$("#last-two-months-td").text(lastTwoMonths);
这个经历很感叹,要实现功能很简单,但你是开着宝马到终点的还是骑着单车到终点的就是重大区别。而且这个宝马还可以拓展(就是如果你想得到上几个月,还可以用循环弄出来),那是更大的区别了。我反思过,我写不出这样的代码,是对变量的运用不熟悉。我是知道变量是怎样用的,但没这样用过一时很难想到。高手总是说写出优雅的代码,我终于有点明白优雅这个词为什么能放到代码上了。一个方法,命名清晰,效率够高,可拓展性好,重用性高,那就是大大的优雅。而我写的东西,需求一变化,改起来又麻烦,就是拓展性差,维护起来困难,又不能拿到其他地方去用,只能针对这个功能用,就是重用性很低。
关于写出优雅代码,上网看到大家评价不错的好书,准备有时间要搞回来膜拜:
1.编写可读代码的艺术
2.代码整洁之道
3.程序员修炼之道