首页 > 解决方案 > 防止重复和写得更短

问题描述

我检查了三个元素的可用性。如果它们被定义,我会对每个元素执行相同的操作。我想避免重复代码。我怎样才能以更短、更有效的方式编写它?

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;
}

标签: javascript

解决方案


你有正确的想法,这应该是浓缩的。您可以通过将变量数据作为参数传递给函数并根据这些参数值做出决策来做到这一点。

您也不需要明确检查!=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.');

推荐阅读