未满足 Javascript forEach() 方法中的一系列条件时的条件

问题描述 投票:0回答:2

我的

IntersectionObserver
使用
forEach
方法来调用一些函数,如果数组的每个项目都满足条件:

  const sections = document.querySelectorAll("section")

  function removeHighlight(id) {
    someElementArray[id].classList.remove('highlight')
  }

  function addHighlight(id) {
    someElementArray[id].classList.add('highlight')
  }

  function onObserve(entries, observer) {
    entries.forEach((entry) => {
       if (entry.isIntersecting) {
          const { id } = entry.target
          removeHighlight(selectedId)
          addHighlight(id)
          selectedId = id
       }
    })
  }

  const observer = new IntersectionObserver(onObserve, options)
  sections.forEach((section) => {
      observer.observe(section)
   })

当任何数组项不满足此条件时,我可以在

onObserve
回调中使用逻辑吗?如:

  function onObserve(entries, observer) {
    entries.forEach((entry) => {
       if (entry.isIntersecting) {
          const { id } = entry.target
          removeHighlight(selectedId)
          addHighlight(id)
          selectedId = id
       }
    })
    // otherwise, if none of the items meet the condition
    // do something else
  }
javascript arrays foreach
2个回答
0
投票

您可以通过对条目数组使用“every”方法来检查是否没有条目满足条件。 every 方法测试数组中的所有元素是否都通过提供的函数。如果任何条目不相交,则可以执行特定逻辑。以下是修改 onObserve 函数的方法:

function onObserve(entries, observer) {
  const isAnyIntersecting = entries.some(entry => entry.isIntersecting);

  if (isAnyIntersecting) {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const { id } = entry.target;
        removeHighlight(selectedId);
        addHighlight(id);
        selectedId = id;
      }
    });
  } else {
    // If none of the items meet the condition
    // Do something else
  }
}

在上面的示例中,“some”方法用于检查是否至少有一个条目相交。如果 isAnyIntersecting 为 true,则表示至少有一项满足条件,并执行 if 块内的逻辑。如果为 false,则执行 else 块内的逻辑,表明没有任何项目满足条件。


0
投票

你可以尝试这样的事情:

function onObserve(entries, observer) {
    const allEntriesIntersecting = entries.every((entry) => entry.isIntersecting);

    if (allEntriesIntersecting) {
        entries.forEach((entry) => {
            const { id } = entry.target;
            removeHighlight(selectedId);
            addHighlight(id);
            selectedId = id;
        });
    } else {
        // do something else when not all entries meet the condition
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.