首页 > 解决方案 > 有没有办法避免这段代码中的嵌套循环?

问题描述

我正在构建一个 chrome 扩展,允许用户用小图像替换单词。这是我的代码。

lookup=[['text','img.png']...];
var text = document.querySelectorAll('h1,h2,h3,h4,h5,p,li,td,caption,span,a')

for (let i=0; i< text.length; i++) {
    var height = window.getComputedStyle(text[i]).fontSize
    for (let j=0;j<lookup.length;j++){
        text[i].innerHTML = text[i].innerHTML.replace(new RegExp(lookup[j][0],"gi"),"<img src=\"img/"+lookup[j][1]+"\" width=\""+height+"\" height=\""+height+"\">");
    }
}

由于每次页面中的任何文本更改时都必须运行此代码,我担心嵌套循环可能会导致严重的性能下降。javascript中有什么可以避免的吗?

标签: javascripttime-complexity

解决方案


您可以创建一个对象查找并使用alternation 创建一个正则表达式|。使用函数作为第二个参数,根据匹配replace使用对象获取图像lookup

const lookup= { 'text': 'img.png' },
      elements = document.querySelectorAll('h1,h2,h3,h4,h5,p,li,td,caption,span,a'),
      regex = new RegExp(Object.keys(lookup).join("|"), 'gi')

elements.forEach(e => {
  const height = window.getComputedStyle(e).fontSize;
  e.innerHTML = e.innerHTML.replace(regex, m => `<img src="img/${lookup[m]}" width="${height}" />`)
})

推荐阅读