如何終止 javascript forEach()?


你無法跳出 forEach 方法,它也沒有提供退出迴圈的方法(除了丟擲異常)。

你可以改用其他功能,如 lodash 中的 _.find −

_.find − 當找到元素時,會退出迴圈。例如,

示例

_.find([1, 2, 3, 4], (element) => {
   // Check your condition here
   if (element === 2) {
      return true;
   }
   // Do what you want with the elements here
   // ...
});

forEach 中丟擲異常。例如,

示例

try {
   [1, 2, 3, 4].forEach((element) => {
      // Check your condition here
      if (element === 2) {
         throw new Error();
      }
      // Do what you want with the elements here
      // ...
   })
} catch (e) {
   // Do nothing.
}

更新於: 27-11-2019

454 瀏覽量

提升你的 職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.