javascript - 我可以使用正则表达式来计算一年的世纪吗?
问题描述
创建一个接收一年并返回正确世纪的函数。所有年份都在 1000 到 2010 年之间。11 世纪在 1001 到 1100 年之间。18 世纪在 1701 到 1800 年之间。
有没有办法使用正则表达式来做到这一点?我知道这很长,但我只是想适应正则表达式。
function century(num) {
if (/1000/ig.test(num) === true) {
return '10th century';
} else if (/[1001-1100]/ig.test(num) === true) {
return '11th century';
} else if (/[1101-1200]/ig.test(num) === true) {
return '12th century';
} else if (/[1201-1300]/ig.test(num) === true) {
return '13th century';
} else if (/[1301-1400]/ig.test(num) === true) {
return '14th century';
} else if (/[1401-1500]/ig.test(num) === true) {
return '15th century';
} else if (/[1501-1600]/ig.test(num) === true) {
return '16th century';
} else if (/[1601-1700]/ig.test(num) === true) {
return '17th century';
} else if (/[1701-1800]/ig.test(num) === true) {
return '18th century';
} else if (/[1801-1900]/ig.test(num) === true) {
return '19th century';
} else if (/[1901-2000]/ig.test(num) === true) {
return '20th century';
} else if (/[2001-2100]/ig.test(num) === true) {
return '21th century';
} else {
return undefined;
}
}
console.log(century(1756)); //"18th century"
console.log(century(1555)); //"16th century"
console.log(century(1000)); //"10th century"
console.log(century(1001)); //"11th century"
console.log(century(2005)); //"21th century"
解决方案
不需要正则表达式,甚至不需要冗长的比较字符串。一些简单的算术将完成这项工作:
let year = window.prompt("What year?");
let century = Math.floor((year-1)/100)+1
console.log(century+'th century');
// e.g. 18th century
我意识到,当我们进入 21 世纪时,这会以较小的方式失败。你可以解决这个问题!
推荐阅读
- excel - Div 类的 VBA 代码
- sql - SQL Server - 在按特定列分组时构建动态数字范围
- client - on_message 使我的所有 bot.commands 停止工作
- sql-server - 通过 SQL Server 代理作业通过控制台应用程序执行 SSRS 报告
- php - Vuejs 从 PHP/MySQL 获取请求不起作用
- php - PHP中JSON多维数组的访问值
- google-sheets - 在一个数组中,返回除一个以外的所有值
- ruby - 通过 Scoop 在 AppVeyor CI 上安装某些工具时出现构建错误
- gradle - Gradle:在某个任务中顺序执行任务
- python-3.6 - Python3.6 如何逐行阅读并用逗号分隔这些行?