javascript - 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;
}
}
}
我遇到的问题是我有代码味道,有这么多如果,否则,有人可以帮我使它更短和可重用吗?谢谢
解决方案
我会这样写:
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
推荐阅读
- tensorflow - autokeras 模型转换为 tensorflowjs 模型
- python - 列表理解而不是嵌套的 for 循环
- monitoring - 如何显示前 K 个节点 wrt CPU 使用率?
- git - 使用 Github Actions 持续部署到 Heroku
- html - Gatsby 按钮 onClick 使用链接功能
- java - 将 onItemClickListener 放在 AutoCompleteTextView 下拉列表中并通过获取位置传递意图但失败
- javascript - Oribt 控件不起作用,鼠标无法移动场景
- android-popupwindow - 在另一个视图下方显示 Android 弹出窗口
- c# - WPF DataGrid 标题文本背景填充
- javascript - JSON.filter(...).then 不是函数(Javascript)