javascript实现快速映射,类似这样:
let config = {
'年|year|nian': 'year',
'月|month|yue': 'month'
}
function a(type) {
type = config[type]; // 只要type能和映射表某一键值匹配,则能快速映射为另一个值
console.log(type);
}
a('年');
a('month');
a('year');
这样不用写if else,并且后续维护也比较简单,只要添加或者删除映射表里的映射规则即可
下面是我实现的映射方法,但是这样写效率太低了,每次都要遍历,而且都要new一个正则对象
let config = {
'年|year|nian': 'year',
'月|month|yue': 'month'
};
function getType(type) {
let tstr,
treg;
type = type + '';
for (tstr in config) {
treg = new RegExp(tstr, 'g');
if (treg.test(type)) {
return config[tstr];
}
}
}
幕布斯6054654
相关分类