【问题标题】:How to use another function to stop a foreach loop如何使用另一个函数来停止 foreach 循环
【发布时间】:2021-07-29 21:05:26
【问题描述】:

我正在使用 foreach 循环调用一个 php 页面,该页面发送回一个画廊图像的 html。 forEach 循环由函数 galleryplayer 触发。图库大小可以是最多 1 到 99 张照片。

我想使用函数 stopGalPlay 来停止当前正在进行的迭代中的 foreach 循环。然而,在尝试解决这个问题一周后,我想不出怎么解决。

阅读后,共识说我不应该使用 forEach 循环。如果是这样,我将如何重写 galleryPlayer 函数以使用不同类型的循环和/或合并一些机制来打破循环并执行 stopGalPlay 函数中的代码。

我知道打破 foreach 循环的问题之前已经回答了一百万次,但我不知道如何将停止播放合并到我的图片库中。

任何帮助将不胜感激。 请注意,我想使用没有 jquery 或其他库等库的纯 javascript。

var detailPageTabContentContainer = document.getElementById("detailPageTabContentContainer");

// Open the Modal
function openGalleryModal(galId, count, rowTotal) {
  var galId = arguments[0];
  var count = arguments[1];
  var rowTotal = arguments[2];
  const api_url = "includes/ajax/GalleryViewerXhr.php?galId=" + galId + "&&count=" + count + "&&rowTotal=" + rowTotal;
    fetch(api_url, { method: 'get', credentials: 'same-origin' })
      .then(response => response.text())
      .then(html => {
    detailPageTabContentContainer.innerHTML = html;
  })
      .catch((err) => console.log("Can’t access " + api_url + err));
} // End of function openGalleryModal


// Close the Modal
function closeGalleryModal() {
  document.getElementById("galleryModal").style.display = "none";
  document.getElementById("active").click();
} // End of function closeGalleryModal


function plusGallerySlides(galId, count, rowTotal, n) {
  var galId = parseInt(arguments[0]);
  var count = parseInt(arguments[1]);
  var rowTotal = parseInt(arguments[2]);
  var n = (arguments[3]);
  var GalIdFragment = (Math.floor(galId / 100));
  var GalIdFragmentString = GalIdFragment.toString();
  var countString;
  if (count + n > rowTotal) {newCount = 1}
  if (count + n < 1) {newCount = rowTotal}
  if (count + n == rowTotal) {newCount = rowTotal}
  if ((count + n < rowTotal)&&(count + n != 0)) {newCount = count + n}
  if (count.toString().length == 1) {countString = "0" + count}
  else {countString = count}
  if (newCount.toString().length == 1) {countString = "0" + newCount } else {countString = newCount};
  countString = countString.toString();
  newGalId = GalIdFragmentString + countString;
  const api_url = "includes/ajax/GalleryViewerXhr.php?galId=" + newGalId + "&&count=" + newCount + "&&rowTotal=" + rowTotal;
    fetch(api_url, { method: 'get', credentials: 'same-origin' })
      .then(response => response.text())
      .then(html => {
    detailPageTabContentContainer.innerHTML = html;
  })
      .catch((err) => console.log("Can’t access " + api_url + err));
} // End of function plusGallerySlides


function stopGalPlay(galId, count, rowTotal) {
  var galId = parseInt(arguments[0]);
  var count = parseInt(arguments[1]);
  var rowTotal = parseInt(arguments[2]);
  console.log("gallery Id is " + galId + ". Count is " + count + ". Row total is " + rowTotal + ".");
  const api_url = "includes/ajax/GalleryViewerXhr.php?galId=" + galId + "&&count=" + count + "&&rowTotal=" + rowTotal;
    fetch(api_url, { method: 'get', credentials: 'same-origin' })
      .then(response => response.text())
      .then(html => {
    detailPageTabContentContainer.innerHTML = html;
  })
      .catch((err) => console.log("Can’t access " + api_url + err));
}


function galleryplayer(galId, count, rowTotal) {
  var galId = parseInt(arguments[0]);
  var count = parseInt(arguments[1]);
  var rowTotal = parseInt(arguments[2]);
  var GalIdFragment = (Math.floor(galId / 100));
  var GalIdFragmentString = GalIdFragment.toString();
  var galIdArr = [];
  for ( i = 1; i <= rowTotal ; i++ ) {
   galIdArr.push(i < 10 ? (GalIdFragmentString + "0" + i.toString()) : GalIdFragmentString + i.toString())
  };
  var interval = 4950;
  var promise = Promise.resolve();
    galIdArr.forEach(function (ArrayGalId, i) {
    promise = promise.then(function() {
      const api_url = "includes/ajax/GalleryViewerXhr.php?galId=" + ArrayGalId + "&&count=" + (i+1) + "&&rowTotal=" + rowTotal;
        fetch(api_url, { method: 'get', credentials: 'same-origin' })
          .then(response => response.text())
          .then(html => {
        detailPageTabContentContainer.innerHTML = html;
        document.getElementById("galNext").style.display = "none";
        document.getElementById("galPrev").style.display = "none";
        document.getElementById("galPlay").style.display = "none";
        document.getElementById("galClose").style.display = "none";
        document.getElementById("galPhoto").classList.add("Gallery-Player-Fade-in-Out");
      })
      return new Promise(function(resolve) {
        setTimeout(resolve, interval);
        if((i+1) === (galIdArr.length)) {
          var lastGalId = (galIdArr[galIdArr.length -1]);
          var galLength = galIdArr.length;
          const api_url = "includes/ajax/GalleryViewerXhr.php?galId=" + lastGalId + "&&count=" + galLength + "&&rowTotal=" + rowTotal;
            fetch(api_url, { method: 'get', credentials: 'same-origin' })
            .then(response => response.text())
            .then(html => {
          detailPageTabContentContainer.innerHTML = html;
          });
        };
      });
    });
  }); 
}// End of function galleryplayer

【问题讨论】:

  • 如果你想摆脱迭代,不要使用forEach。使用普通的 for(...){} 循环,它可以让您通过循环条件和 break 关键字明确控制何时停止。
  • 是的,我有点倾向于不使用 forEach 循环,但我无法让 for 循环与 Promise 一起工作。不知道如何使用 stopGalPlay 函数触发中断。
  • 首先将代码简化为minimal reproducible example,至少对于stackoverflow而言。至于承诺:它们无关紧要,任何 JS 都可以访问所有本地和更高范围的范围,因此只需声明您的控制变量(但更好的是,具有多个与特定运行相关联的控制变量的控制器对象)您的 for 循环可以检查同一范围内的其他代码可以更新。
  • 感谢反馈。我想我明天会重新开始使用 GalleryPlayer 函数,看看我是否可以让它做同样的事情,但要使用 for 循环。

标签: javascript loops foreach


【解决方案1】:

您可以使用 while 循环。虽然这个条件是假的,但这样做。或者你可以将 forEach 循环放在一个函数中,并在它应该中断时返回。

【讨论】:

  • 不,你不能。在 forEach 中返回等效于 continue,而不是 break。其余的迭代仍将运行。即使那些返回。
【解决方案2】:

使用 [].some 代替 [].forEach

只要你想打破它,只需返回 true;它将停止执行以进行进一步的迭代。

例如

[].forEach(v => {
...
 break; // does not work; 
....
})

[].some(v => { // some work same as foreach if you don't return true;
....
return true; // will stop the iteration.
....
});

【讨论】:

    猜你喜欢
    • 2018-12-30
    • 2021-09-15
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多