3 回答
TA贡献1993条经验 获得超5个赞
是的,可以通过多种方式改进此代码。此外,为了比较日期,我们将使用Date实例,这是处理日期和时间的内置 JS 方法。
var monthName = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
首先,我们不需要列出月份数字,因为我们可以使用上面数组的数组索引(从 0 到 11),它将给我们带来好处。
现在让我们从 URL 解析月份和年份。我们将使用正则表达式来编写更少的代码:
const matches = window.location.href.match(/http:\/\/www.website.com\/blog\/([0-9]{4})\/([a-z]{3,})\.html/);
// String.prototype.match, which we used can give us null value if URL doesn't match our pattern, so we need to check it first.
if (matches !== null) {
const year = parseInt(matches[0]); // the first match of regular expression is the year
const monthIndex = monthName.indexOf(matches[1]); // this should give us the number of month, from 0 to 11
if (monthIndex !== -1) { // but we must continue only if month name in the URL is correct.
const date = new Date(); // Get current date.
// Now let's extract month and year from the current date.
// date.getMonth() returns the current number of month from 0 to 11, just what we need.
// date.getFullYear() obviously returns the current year number.
// Let's use these methods and compare current date values with ones we've got from the URL:
if (date.getFullYear() > year || (date.getFullYear() === year && date.getMonth() > monthIndex)) {
// we're in the future, let's redirect:
window.location.href = 'https://website.com/error.html';
}
}
}
TA贡献1863条经验 获得超2个赞
我会像你指定的那样做。清晰、明显的逻辑是最容易维护的。
function isFutureURL(url) {
// Month name array
let months = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
// Parse the URL for the year and month
let b = url.split(/\/|\./);
let y = b[6];
let m = months.indexOf(b[7]);
// Set URL date to 00:00:00 at start of URL month
let urlDate = new Date(y, m, 1);
// Return true if test date is after current date
// I.e. it's the first of next month or greater
return urlDate > Date.now();
}
['http://www.website.com/blog/2018/april.html',
'http://www.website.com/blog/2019/october.html',
'http://www.website.com/blog/2020/may.html'
].forEach(sampleURL =>
console.log(sampleURL + '\n is in the future? ' + isFutureURL(sampleURL))
);
这假设月份和年份将始终位于 URL 中的同一位置,您可能需要考虑使之更可靠的选项(例如,在 URL 的任何位置查找月份名称和有效年份)。
您可能还想对 URL 以及y和m 的值进行一些验证,以避免用户看到错误。
TA贡献1998条经验 获得超6个赞
使用 if 条件
例如,让来源为:http : //www.website.com/blog/2019/october.html
获取 currMonthNo 和 curryear 从
var d = new Date();
并同时获得srcMonthNo从sourceurl
现在检查
if(source.indexof(curryear) > -1 && currMonthNo <= srcMonthNo) {
// Then return your conditional code
} else {
// Return error message
}
添加回答
举报