Javascript 有没有办法避免代码中的嵌套循环?
我正在构建一个chrome扩展,允许用户用微小的图像替换文字。这是我的密码Javascript 有没有办法避免代码中的嵌套循环?,javascript,time-complexity,Javascript,Time Complexity,我正在构建一个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
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+"\">");
}
}
lookup=[['text','img.png']…];
var text=document.querySelectorAll('h1,h2,h3,h4,h5,p,li,td,caption,span,a')
for(设i=0;i 对于(让j=0;j您可以创建一个对象查找,并创建一个带有alternation|
的正则表达式。使用函数作为replace
中的第二个参数,并使用查找
对象根据匹配获取图像
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}" />`)
})
const lookup={'text':'img.png'},
elements=document.queryselectoral('h1,h2,h3,h4,h5,p,li,td,caption,span,a'),
regex=newregexp(Object.keys(lookup.join(“|”),“gi”)
elements.forEach(e=>{
常量高度=window.getComputedStyle(e).fontSize;
e、 innerHTML=e.innerHTML.replace(regex,m=>``)
})
不能用CSS替换其中的一部分吗?CSS可以只将新文本更改为图像,您不需要重新创建整个页面。@Teemu我不太熟悉CSS