javascript - 防止重复和写得更短
问题描述
我检查了三个元素的可用性。如果它们被定义,我会对每个元素执行相同的操作。我想避免重复代码。我怎样才能以更短、更有效的方式编写它?
const studentElem = component.find("students").getElement();
if (studentElem != undefined) {
let studentNoice = studentElem.innerText;
studentNoice = studentNoice.replace('classNo', 'Reg No.');
studentElem.innerHTML = studentNoice;
}
const staffElem = component.find("staff").getElement();
if (staffElem != undefined) {
let staffNoice = staffElem.innerText;
staffNoice = staffNoice.replace('staffNo', 'Staff Rec.');
staffElem.innerHTML = staffNoice;
}
const parentElem = component.find("parents").getElement();
if (parentElem != undefined) {
let parentNoice = parentElem.innerText;
parentNoice = parentNoice.replace('ParentID', 'P-ID.');
parentElem.innerHTML = parentNoice;
}
解决方案
你有正确的想法,这应该是浓缩的。您可以通过将变量数据作为参数传递给函数并根据这些参数值做出决策来做到这一点。
您也不需要明确检查!=undefinded
. 您可以只检查元素的存在if(elem)
。.innerHTML
并且,当您正在使用的字符串不包含任何 HTML 时不要使用,因为这.innerHTML
会影响安全性和性能。改为使用.textContent
。
来自MDN:
插入纯文本时建议不要使用innerHTML;相反,使用 Node.textContent。这不会将传递的内容解析为 HTML,而是将其作为原始文本插入。
function foo(role, find, replace){
const elem = component.find(role).getElement();
// No need to check for !=undefined because that essentially means
// you are checking for a "truthy" value, which is what an if condition
// checks for by default, so checking the variable itself forces the
// value to be converted to a Boolean. If the element exists, the Boolean
// becomes true and if not, it is false.
if (elem) {
// Setting up variables that are only used once is a bit of a waste
// Just do the work here and there's less code to write and maintain
elem.textContent = elem.textContent.replace(find, replace);
}
}
// You then call the function and pass the variable data
foo("students", 'classNo', 'Reg No.');
foo("staff", 'staffNo', 'Staff Rec.');
foo("parents", 'ParentID', 'P-ID.');
推荐阅读
- python - NumPy FFT 产生偏离中心的输出
- android - 将视图从 ConstraintLayout 中的重叠移开(最小约束)
- kubernetes - 在 Kubernetes 中的 PVC 中,您会在哪种实际场景中使用 ReadWriteOnce 而不是 ReadWriteMany?
- java - 为什么我不能在 Eclipsed 中调试 NodeList?
- amazon-web-services - AWS Elastic Beanstalk 更新超时
- api - 需要从 Collibra 导出数据集
- mysql - 使用 MySQL 查询执行计划检测 SQL 注入
- couchbase-indexing - Couchbase 返回 "{"msg":"Keyspace USE_Apps 上没有与您的查询匹配的索引
- python - 使用 python 3.8+(默认协议=5)时,pickle.load 在 python 3.7 中的(协议=4)对象上失败
- php - 获取 PDF 文件内容:“格式错误的 UTF-8 字符,可能编码不正确”