如何解决为什么 forEach 不起作用,而 for 循环却起作用?原生 JavaScript
谁能解释一下为什么 for 循环有效,而 forEach 无效。我以为我们可以简单地换用 forEach 没有问题。
它有效! FOR 循环
const logoPics = document.querySelectorAll('.logo__pic,.home__pic');
logoPics.forEach(logoPic => {
let logoPicChildren = logoPic.children;
for (let i = 0; i < logoPicChildren.length; i++) {
logoPicChildren[i].outerHTML = logoPicChildren[i].outerHTML.replace(/logo-official/g,'logo-official-light');
logoPicChildren[i].outerHTML = logoPicChildren[i].outerHTML.replace(/logo-alternative/g,'logo-alternative-light');
logoPicChildren[i].outerHTML = logoPicChildren[i].outerHTML.replace(/logo-transparent/g,'logo-transparent-light');
}
});
它仅更改“徽标官方”。 FOREACH
const logoPics = document.querySelectorAll('.logo__pic,.home__pic');
logoPics.forEach(logoPic => {
let logoPicChildren = Array.from(logoPic.children);
logoPicChildren.forEach(logoPicChild => {
logoPicChild.outerHTML = logoPicChild.outerHTML.replace(/logo-official/g,'logo-official-light');
logoPicChild.outerHTML = logoPicChild.outerHTML.replace(/logo-alternative/g,'logo-alternative-light');
logoPicChild.outerHTML = logoPicChild.outerHTML.replace(/logo-transparent/g,'logo-transparent-light');
})
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。