首页 > 开发 > NodeJS > 正文

一段js代码的简写问题

2017-09-08 17:22:52  来源:网友分享
    options.filename = dbPath+'picker';    pickerDB = new Datastore(options);    options.filename = dbPath+'data';    dataDB = new Datastore(options);    options.filename = dbPath+'web';    webDB = new Datastore(options);    options.filename = dbPath+'url';    urlDB = new Datastore(options);    options.filename = dbPath+'attach';    attachDB = new Datastore(options);    options.filename = dbPath+'cacheUrl';    cacheUrlDB = new Datastore(options);    options.filename = dbPath+'cache';    cacheDB = new Datastore(options);    options.filename = dbPath+'cron';    cronDB = new Datastore(options);    options.filename = dbPath+'log';    logDB = new Datastore(options);    options.filename = dbPath+'cronLog';    cronLogDB = new Datastore(options);

请教一下,这一大段,都是复制粘贴。能用更简洁的代码一次搞定吗?

解决方案

不知道算不算你心中的简写,我觉得从重复的角度看,把不同的部分提取出来做个数组,把相同的部分抽象,如下:

let options = {},    dbPath = ''; //TBD by yourselflet stores = [    'picker',    'data',    'web',    'url',    'attach',    'cacheUrl',    'cache',    'cron',    'log',    'cronLog']    .map(key => (options.filename = dbPath + key, new Datastore(options)));console.log(stores); //stores you want