为什么 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 (将#修改为@)