node.js - 一段js代码的简写问题

查看:142
本文介绍了node.js - 一段js代码的简写问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题


    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 yourself

let 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

这篇关于node.js - 一段js代码的简写问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆