Javascript 中的嵌套字符串文字

Nested string literals in Javascript

我正在尝试创建一个函数来接受 2 个参数和 return 一个模板字符串。如果发生这种情况:window.location.href.endsWith('BRONCHOSCOPY'),我想 运行 生成下面代码的函数(但需要根据第二个参数更改 procedure1 编号以从数组中提取值)。

if (window.location.href.endsWith('BRONCHOSCOPY')) {
    extraInfo.innerHTML = `<b>${thoracics.procedures.procedure1.extraInfo}</b>`;
    procedure.innerHTML = `<b>${thoracics.procedures.procedure1.name}<b>`;
    firstColumn.innerHTML = `${thoracics.procedures.procedure1.textFirstColumn}`;
    secondColumn.innerHTML = `${thoracics.procedures.procedure1.textSecondColumn}`;
    icon.innerHTML = `<img src="${thoracics.src}" width="40" height="40" class="d-inline-block align-top" alt="${thoracics.alt}' loading="lazy"></img>`; 
}

我有这样的功能:

 function procedureInfo(arg, x) {
    return `extraInfo.innerHTML = <b>${${arg}.procedures.procedure.extraInfo}</b>
    procedure.innerHTML = <b>${${arg}.procedures.procedure${x}.name}<b>
    firstColumn.innerHTML = ${${arg}.procedures.procedure${x}.textFirstColumn}
    secondColumn.innerHTML = ${${arg}.procedures.procedure${x}.textSecondColumn};
    icon.innerHTML = <img src="${${arg}.src}" width="40" height="40" class="d-inline-block align-top" alt="${${arg}.alt}' loading="lazy"></img>`
  }

JS 不喜欢这种语法,比如嵌套数组,我相信有更简单的方法来做到这一点。

请记住,使用动态内容设置 innerHTML 是危险的,因为它会在您的应用程序中创建 XSS vulnerability

考虑到这一点,为什么不return这样的函数呢?

function procedureInfo(arg, x) {
  return () => {
    const procedure = arg.procedures[`procedure${x}`];

    extraInfo.innerHTML = `<b>${procedure.extraInfo}</b>`;
    procedure.innerHTML = `<b>${procedure.name}<b>`;
    firstColumn.innerHTML = procedure.textFirstColumn;
    secondColumn.innerHTML = procedure.textSecondColumn;
    icon.innerHTML = `<img src="${arg.src}" width="40" height="40" class="d-inline-block align-top" alt="${arg.alt}" loading="lazy" />`;
  };
}

const code = procedureInfo(thoracics, 1);

// later...
// instead of eval(code);
code();

您还可以考虑使 thoracics.procedures 成为一个数组而不是具有编号属性的对象,以简化访问适当嵌套属性的逻辑。