javascript - 有没有办法避免这段代码中的嵌套循环?
问题描述
我正在构建一个 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中有什么可以避免的吗?
解决方案
您可以创建一个对象查找并使用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}" />`)
})
推荐阅读
- c# - Rhino Mocks Stub 不调用 .WhenCalled 操作
- swift - 为什么在 Swift 中通过 Selector 调用时函数的默认参数不被尊重?
- database - 当数据类具有内部类时,房间数据库表创建错误
- header-files - python3.7-dev和python3-dev头文件的区别
- c# - csvhelper - 如何为复杂对象创建映射器
- c - 如何在不使用 stdio.h 的情况下读取 txt 文件的最后 n 个字符?
- swift - 初始化程序的问题:在 super.init 调用时未初始化属性“self.options”
- vim - 范围声明后的 Vim cindent 不起作用
- reactjs - 如何修复'从源'http://localhost:3000' 访问'http://localhost:8000/api/companies' 的 XMLHttpRequest 已被 CORS 策略阻止'
- apache-flink - Flink 请求/响应模式可以结合源/接收器吗?