【问题标题】:Is there a better way to check a flag and then set optional parameter in a function in javascript? (Writing function in a js object)有没有更好的方法来检查标志,然后在 javascript 的函数中设置可选参数? (在js对象中编写函数)
【发布时间】:2021-04-02 22:59:24
【问题描述】:

我在做一个电子项目时遇到了这种情况。下面是一个 pouchDB put 函数,我正在尝试用它上传附件

我现在的代码是这样的:

testCasesDB.put({
  _id: String(info.doc_count),
  collectionID: String(collectionID),
  name: String(tName),
  description: String(tDescription),
  performed: tPerform,
  added: tAdd,
  _attachments: {
    testCaseFile: {
      type: tAttachment.type,
      data: tAttachment,
    },
  },
  // ...
});

问题是我想检查变量 tAttachment 是否设置。如果不是,我不想在 pouchDB 中添加附件,如果设置了它,我希望它如上所述。为此,我通常会编写两个重复的代码并添加 _attachment 选项。我想知道是否有更好的方法来做到这一点。像这样的东西? (以下行不通):

testCasesDB.put({
  _id: String(info.doc_count),
  collectionID: String(collectionID),
  name: String(tName),
  description: String(tDescription),
  performed: tPerform,
  added: tAdd,
  _attachments: {
    testCaseFile: {
      function() {
        if (tAttachment) {
          returnData = {
            type: tAttachment.type,
            data: tAttachment,
          };
        } else {
          returnData = null;
        }
        return returnData;
      },
    },
  },
});

【问题讨论】:

  • 您的解决方案真的有效吗?对我来说似乎是狡猾的代码
  • @badsyntax 不,第二个代码代表我打算做什么。我目前的解决方案是检查选项之外的附件变量

标签: javascript performance electron pouchdb


【解决方案1】:

我可能会在创建新实体之前声明附件映射:

const attachments = {};

if (tAttachment) {
  attachments.testCaseFile =  {
    type: tAttachment.type,
    data: tAttachment,
  }
}

testCasesDB.put({
  _id: String(info.doc_count),
  collectionID: String(collectionID),
  name: String(tName),
  description: String(tDescription),
  performed: tPerform,
  added: tAdd,
  _attachments: attachments,
  // ...
});

【讨论】:

    猜你喜欢
    • 2010-09-14
    • 1970-01-01
    • 2011-12-08
    • 2020-04-05
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多