优化代码,由于数组中的字符串在代码两处是用直接写死字符串的方式引用,拼写错误会造成潜在BUG。故将一个数组变成一个json便于调用。
module.exports = { PM: ['/getmyitems', '/getwardrobe', '/additem', '/moveitem', '/exchangeitem', '/splititem', '/mergeitem', '/pickitem', '/dropitem', '/takeon', '/takeoff', '/takeonclothing', '/takeoffclothing', '/deleteitem', '/clearitem', '/find', '/setbulidlev', '/fly', '/chgmap', '/flytonpc', '/setpopulation', '/setfood', '/settime', '/setbuildtimes', '/addmoney', '/submoney', '/setsignature', '/addtitle', '/createprofession', '/changeprofession', '/chgattr', '/buildupgrade', '/buildset', '/builddel', '/buildadd', '/buildput', '/homeupgrade', '/createprofession'],// PM命令 全部小写 PM_COMMAND: { GETMYITEMS: '/getmyitems', GETWARDROBE: '/getwardrobe', ADDITEM: '/additem', MOVEITEM: '/moveitem' // 手动复制粘贴到这儿后,才想到可以通过代码对数组进行转换,以前的工作中,其实常常有用到转换,但是都是业务需求,像这次代码优化,转换的需求并不是业务上的需求,只是手动写了几个大写字母后,看到还有那么多字符串要手动写,自然而然就想到了用代码解决,这算是一次工作技能应用到了生活需求上,虽然最终目的还是为了工作上的优化,特此纪念 } };
下面是转换过程和结果:
var PM = ['/getmyitems', '/getwardrobe', '/additem', '/moveitem', '/exchangeitem', '/splititem', '/mergeitem', '/pickitem', '/dropitem', '/takeon', '/takeoff', '/takeonclothing', '/takeoffclothing', '/deleteitem', '/clearitem', '/find', '/setbulidlev', '/fly', '/chgmap', '/flytonpc', '/setpopulation', '/setfood', '/settime', '/setbuildtimes', '/addmoney', '/submoney', '/setsignature', '/addtitle', '/createprofession', '/changeprofession', '/chgattr', '/buildupgrade', '/buildset', '/builddel', '/buildadd', '/buildput', '/homeupgrade', '/createprofession']; var UPCase = {}; for (var i = 0; i < PM.length; i++) { var key = PM[i].toLocaleUpperCase().replace("/", ""); UPCase[key] = PM[i]; } console.log(UPCase);
{ GETMYITEMS: '/getmyitems', GETWARDROBE: '/getwardrobe', ADDITEM: '/additem', MOVEITEM: '/moveitem', EXCHANGEITEM: '/exchangeitem', SPLITITEM: '/splititem', MERGEITEM: '/mergeitem', PICKITEM: '/pickitem', DROPITEM: '/dropitem', TAKEON: '/takeon', TAKEOFF: '/takeoff', TAKEONCLOTHING: '/takeonclothing', TAKEOFFCLOTHING: '/takeoffclothing', DELETEITEM: '/deleteitem', CLEARITEM: '/clearitem', FIND: '/find', SETBULIDLEV: '/setbulidlev', FLY: '/fly', CHGMAP: '/chgmap', FLYTONPC: '/flytonpc', SETPOPULATION: '/setpopulation', SETFOOD: '/setfood', SETTIME: '/settime', SETBUILDTIMES: '/setbuildtimes', ADDMONEY: '/addmoney', SUBMONEY: '/submoney', SETSIGNATURE: '/setsignature', ADDTITLE: '/addtitle', CREATEPROFESSION: '/createprofession', CHANGEPROFESSION: '/changeprofession', CHGATTR: '/chgattr', BUILDUPGRADE: '/buildupgrade', BUILDSET: '/buildset', BUILDDEL: '/builddel', BUILDADD: '/buildadd', BUILDPUT: '/buildput', HOMEUPGRADE: '/homeupgrade' }