0
我正在構建一個基於WordPress的應用程序,客戶可以選擇選擇在過去一年中輸入的數據。我很想讓這個代碼更聰明,但我不知道該怎麼做。數據看起來JS是這樣的:通過提供的日期如何比較乾燥的月份?
idsh: Array[4]
0: "565"
1: "565"
2: "567"
3: "569"
length: 4
datesh: Array[4]
0: "12/22/2014 - 00:00:00, 12:00 AM"
1: "01/21/2015 - 00:00:00, 12:00 AM"
2: "01/28/2015 - 00:00:00, 12:00 AM"
3: "02/04/2015 - 00:00:00, 12:00 AM"
length: 4
ids: Array[5]
0: "1009"
1: "979"
2: "1009"
3: "1011"
4: "1013"
length: 5
dates: Array[5]
0: "01/05/2015 - 00:00:00, 12:00 AM"
1: "12/22/2014 - 00:00:00, 12:00 AM"
2: "02/13/2015 - 00:00:00, 12:00 AM"
3: "02/20/2015 - 00:00:00, 12:00 AM"
4: "02/27/2015 - 00:00:00, 12:00 AM"
length: 5
var getQuarters = (function() {
'use strict';
var dates = [
"01/05/2015 - 00:00:00, 12:00 AM",
"12/22/2014 - 00:00:00, 12:00 AM",
"02/13/2015 - 00:00:00, 12:00 AM",
"02/20/2015 - 00:00:00, 12:00 AM",
"02/27/2015 - 00:00:00, 12:00 AM"
];
function loops(items, fn, onLoopComplete) {
var i;
try {
if (items && items.length) {
i = items.length;
} else {
throw new Error(items + ' is required to have a length');
}
if (i > -1) {
do {
if (items[i] !== undefined) {
fn(i);
/* console.log(i + ' is the current iteration'); */
}
}
while (--i >= 0);
}
if (typeof onLoopComplete === 'function') {
onLoopComplete(items.length);
}
} catch (e) {
throw new Error(e);
}
}
function show3() {
loops(dates, function(i) {
var months = dates[i].slice(0, 2),
thisMonth = new Date().getMonth();
if (months == thisMonth ||
months == thisMonth - 1 ||
months == thisMonth - 2) {
console.log(months);
} else {
console.log(dates[i] + ' do not meet criteria.');
}
});
}
function show6() {
loops(dates, function(i) {
var months = dates[i].slice(0, 2),
thisMonth = new Date().getMonth();
if (months == thisMonth ||
months == thisMonth - 1 ||
months == thisMonth - 2 ||
months == thisMonth - 3 ||
months == thisMonth - 4 ||
months == thisMonth - 5) {
console.log(months);
} else {
console.log(dates[i] + ' do not meet criteria.');
}
});
}
return function(quarters) {
switch (quarters) {
case 2:
show6();
break;
case 3:
show9();
break;
case 4:
show12();
break;
default:
show3();
break;
}
};
}());
getQuarters();
我循環,看看他們是否匹配的標準,(如最近3個月),但my code很現在重複。我如何讓它變得更智能和乾爽?
1.您如何*顯示*我們一些代碼? 2.你想*幹*代碼?就像在「不做任何事情,只是打印你會做的事情」一樣? – Siguza
我建議你使用moment.js,它有助於減少代碼。 – Sagar
@Siguza請參閱jsbin的代碼。 - 如果你錯過了:http://jsbin.com/wuzegu/32/edit?js,console – colecmc