首页 > 解决方案 > For循环使其可重用javascript

问题描述

我有一些像这样的循环

for (let i = 0, l = this.documents.length; i < l; ++i) {
  if (item.text !== null) {
    if (this.documents[i].text === item.text) {
      this.documents[i].mandatory = !item.mandatory;
      break;
    }
  } else {
    if (this.documents[i].code === item.code) {
      this.documents[i].mandatory = !item.mandatory;
      break;
    }
  }
}

我遇到的问题是我有代码味道,有这么多如果,否则,有人可以帮我使它更短和可重用吗?谢谢

标签: javascript

解决方案


我会这样写:

let doc  = (item.text !== null)
    ? this.documents.find(d => d.text === item.text)
    : this.documents.find(d => d.code === item.code)

 if (doc)
      doc.mandatory = !item.mandatory

推荐阅读